dsigg21445 2015-04-13 17:31
浏览 39
已采纳

我应该如何在try / catch块中修复此代码气味

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?

  • 写回答

2条回答 默认 最新

  • dongzhong5573 2015-04-13 17:54
    关注

    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;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端