【问题标题】:PHP Mess Detector giving false positivesPHP Mess Detector 给出误报
【发布时间】:2016-02-25 01:55:34
【问题描述】:

我正在处理一个开源项目,并认为使用 phpmd 实现自动代码修订是个好主意。

它向我展示了许多我已经修复的编码错误。但是其中一个让我很好奇。

考虑以下方法:

/**
 * 
 * @param string $pluginName
 */
public static function loadPlugin($pluginName){
    $path = self::getPath()."plugins/$pluginName/";
    $bootPath = $path.'boot.php';
    if(\is_dir($path)){

        //Autoload classes
        self::$classloader->add("", $path);

        //If theres a "boot.php", run it
        if(is_file($bootPath)){
            require $bootPath;
        }

    }else{
        throw new \Exception("Plugin not found: $pluginName");
    }
}

这里,phpmd 说Else is never necessary

...永远不需要带有 else 分支的 if 表达式。你可以 以不需要 else 的方式重写条件,并且 代码变得更易于阅读。 ...

is_dir 将在给定路径是文件或根本不存在时返回 false,因此,在我看来,此测试根本无效。

有没有办法解决它,或者干脆忽略这种情况?

【问题讨论】:

标签: php coding-style conventions phpmd


【解决方案1】:

我不使用phpmd,但很明显您的if 语句是一个保护子句。保护子句不需要else 分支,你可以像这样安全地重构你的代码:

/**
 * @param string $pluginName
 * @throws \Exception if plugin cannot be found
 */
public static function loadPlugin($pluginName)
{
    $path = self::getPath() . "plugins/$pluginName/";
    if (!\is_dir($path)) {
        throw new \Exception("Plugin not found: $pluginName");
    }

    // Autoload classes
    self::$classloader->add("", $path);

    // If there is a "boot.php", run it
    $bootPath = $path . 'boot.php';
    if (is_file($bootPath)) {
        require $bootPath;
    }
}

进一步阅读:

【讨论】:

    【解决方案2】:

    结构的替代方案是这样的:

    public static function loadPlugin( $pluginName ) {
        $path = self::getPath() . "plugins/$pluginName/";
        $bootPath = $path . 'boot.php';
        if( \is_dir( $path ) ) {
            // Autoload classes
            self::$classloader->add( "", $path );
            // If theres a "boot.php", run it
            if ( is_file( $bootPath ) ) {
                require $bootPath;
            }
            // A return here gets us out of the function, removing the need for an "else" statement
            return;
        }
    
        throw new \Exception( "Plugin not found: $pluginName" );
    }
    

    虽然我不确定它是否是解决方案,但它是一种避免else 条件的技术。在尝试阅读代码时,else 条件会增加复杂性,并且允许函数在没有 else 条件的情况下“流动”可以使它们更具可读性。

    【讨论】:

    • 这是一个很好的解决方案,警告不会出现。但是我不得不将 return 移到 if 之外,因为该文件在插件结构中是可选的。
    • 无论如何,我认为删除所有 else 子句并不是一个好主意,因为它是所有编程语言中都存在的基本决策语句。你知道有没有办法在 PHPMd 中禁用这个测试?
    • 我个人不使用 PHPMd。我已经完全喜欢 PHPStorm(它是一个IDE)。太棒了,它提供了代码格式化工具、提示、建议等。我的代码自从使用它后好多了。
    • 感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    相关资源
    最近更新 更多