2

私はオープン ソース プロジェクトに取り組んでおり、自動化されたコード リビジョンをphpmdで実装することをお勧めします。

それは私がすでに修正している多くのコーディングの間違いを示しました。しかし、そのうちの1つが私を興味深くさせました。

次の方法を検討してください。

/**
 * 
 * @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 は決して必要ないと言っています

...else ブランチを含む if 式は必要ありません。else が不要になるように条件を書き直すことができ、コードが読みやすくなります。...

is_dir指定されたパスがファイルであるか、単に存在しない場合は常に false を返すため、私の意見では、このテストはまったく有効ではありません。

それを修正する方法はありますか、またはこのようなケースを単に無視する方法はありますか?

4

2 に答える 2

2

は使用しませんが、あなたのステートメントがガード句であることは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;
    }
}

参考文献:

于 2016-03-06T06:03:02.527 に答える
1

構造の代替は次のようなものです。

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 条件なしで関数を「フロー」できるようにすると、コードが読みやすくなります。

于 2016-02-25T01:58:07.637 に答える