简体   繁体   English

我应该如何在try / catch块中解决此代码异味

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

OK. 好。 I get a code smell warning in my IDE. 我在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. 我不会在try块之外返回任何值。 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. 看来您这样做是为了避免返回任何东西,这当然是您的IDE抱怨的。 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. 在诸如Java之类的静态类型语言中,您必须声明一个返回类型,并且无论如何都要返回一些内容。 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. 我们在PHP中没有这些问题,因此您可以做到这一点,但是肯定可以闻到。 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. 在您尝试/捕获之后,我将返回null,并始终检查从该函数返回的值,无论它在哪里使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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