为什么干净的代码禁止其他表达

Pas*_*cal 16 php phpmd

我在函数中有这个代码:

if ($route !== null) { // a route was found
    $route->dispatch();
} else {
    // show 404 page
    $this->showErrorPage(404);
}
Run Code Online (Sandbox Code Playgroud)

现在PHPmd给出了一个错误:

run方法使用else表达式.否则永远不需要,您可以简化代码,而无需其他工作.

现在我想知道是否真的会更好的代码来避免else而只是在if部分添加一个return语句?

Abi*_*bin 35

PHPMD期望您使用早期的return语句来避免else阻塞.像下面这样的东西.

function foo($access) 
{
    if ($access) {
        return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过将以下内容添加到类doc块来禁止显示此警告.

/**
 * @SuppressWarnings(PHPMD.ElseExpression)
 */
Run Code Online (Sandbox Code Playgroud)

  • 也许我们正在阅读不同的东西,但这就是我正在阅读的内容"当整个三元运算在一条线上时,三元运算符是允许的.更长的三元组应该分成if else语句." 注意'split入if else语句`.多次退货也不是很好 (3认同)
  • 有没有什么论文或任何一种参考资料可以让你看一看,试图理解这个没有别的规则? (2认同)
  • 规则实际上是说要使用Else语句.https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions.md#ternary-operator (2认同)
  • 规则和 PSR 建议表明其他内容没有必要。PHP MD 规则集文档说: 永远不需要带有 else 分支的 if 表达式。您可以以不需要 else 的方式重写条件,并且代码变得更易于阅读。要实现此目的,请使用早期的 return 语句。PSR-2 标准在“编写更好的代码”部分中说:https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions。 md#writing-better-code * 尝试在方法/函数中尽早返回以避免不必要的深度 (2认同)

Joa*_*dan 5

您通常可以重写表达式以仅使用 if 并且主观上确实使代码更具可读性。

例如,如果 showErrorPage 中断代码的执行,则此代码的行为方式相同。

if ($route == null) { 

   $this->showErrorPage(404);
} 
$route->dispatch();
Run Code Online (Sandbox Code Playgroud)

如果 if 语句的内容没有中断执行,则可以添加 return

if ($route == null) { 

   $this->showErrorPage(404);
   return;
} 
$route->dispatch();
Run Code Online (Sandbox Code Playgroud)

如果您在循环中的位置,则可以使用 continue 跳过该迭代

    foreach ($things as $thing ) {
        if ($thing == null) {
            //do stuff and skip loop iteration
            continue;
        }     

        //Things written from this point on act as "else"

    }
Run Code Online (Sandbox Code Playgroud)


gya*_*guy 2

我不会担心 PHPmd 所说的,至少在这种情况下。

他们可能想让你使用条件运算符,因为(在他们看来)它“更干净”。

$route !== null  ?  $route->dispatch() : $this->showErrorPage(404) ;
Run Code Online (Sandbox Code Playgroud)

  • 许多程序员经常建议从 http://www.phptherightway.com/ 学习 (4认同)
  • 怎样才算干净呢?也许在 return 语句或其他东西上,但除此之外与干净的代码完全相反 (2认同)