简体   繁体   中英

How should I fix this code smell in my try/catch block

OK. I get a code smell warning in my IDE. I understand why, and understand that the warning isn't especially dire. However, if there is a better way to write this block, I would like to know.

public function factory($state_name = 'Generic')
{
    ...

    try {
        if (!$class_exists) {
            throw new CustomException;
        } else {
            return new $class_name;
        }
    }
    catch (CustomException $c) {
        echo ...
    }

}

I don't return a value outside of the try block. Smell goes away if I return one at the end. Is there a better way to do this?

The bigger code smell for me is that you are throwing an exception and then immediately catching it. It seems that you are doing this to avoid returning anything, which of course, your IDE is complaining about. I would rewrite this as:

public function factory($state_name = 'Generic')
{
    ...

    if ($class_exists) {
        return new $class_name;
    }
    return null;

}

Your function is a factory and should implicitly return something it created. In statically typed languages such as Java you have to declare a return type, and would have to return something regardless. Your function written in a statically typed language wouldn't compile. We don't have these problems with PHP so you are able to do this, but it is smelly for sure. It's good practice to have your function behave in a consistent manor ie always returning something regardless of what happened. I would return null after your try/catch and always check the value returned from this function wherever it's used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM