【问题标题】:Why does clean code forbid else expression为什么干净的代码禁止else表达式
【发布时间】:2015-09-20 07:48:41
【问题描述】:

我在函数中有这段代码:

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

现在 PHPmd 报错:

方法 run 使用 else 表达式。 Else 从来都不是必需的,并且 您可以简化代码以在没有其他的情况下工作。

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

【问题讨论】:

    标签: php phpmd


    【解决方案1】:

    PHPMD 希望您使用提前返回语句来避免 else 块。类似于以下内容。

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

    您可以通过将以下内容添加到您的类文档块中来抑制此警告。

    /**
     * @SuppressWarnings(PHPMD.ElseExpression)
     */
    

    【讨论】:

    【解决方案2】:

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

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

    if ($route == null) { 
    
       $this->showErrorPage(404);
    } 
    $route->dispatch();
    

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

    if ($route == null) { 
    
       $this->showErrorPage(404);
       return;
    } 
    $route->dispatch();
    

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

        foreach ($things as $thing ) {
            if ($thing == null) {
                //do stuff and skip loop iteration
                continue;
            }     
    
            //Things written from this point on act as "else"
    
        }
    

    【讨论】:

    • 但是如果我不在循环或函数中怎么办?如果我在 WordPress 模板中怎么办?
    • 那我想不出比使用“else”更干净的方法
    【解决方案3】:

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

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

    $route !== null  ?  $route->dispatch() : $this->showErrorPage(404) ;
    

    【讨论】:

    • 那么有什么比phpMD更好的吗?
    • 很多程序员经常建议向phptherightway.com学习
    • 清洁度怎么样?可能在 return 语句或其他地方,但除此之外,与干净的代码完全相反
    【解决方案4】:

    通过结束 404 生产分支删除 else 块:

    if ($route === null) { 
      // show 404 page
      $this->showErrorPage(404);
      return;
    }
    
    // a route was found
    $route->dispatch();
    

    【讨论】:

      【解决方案5】:

      这个答案来晚了,但您可以通过使用else if 来解决这个问题。因为有时你不能只 return 遵循一些逻辑。

      举个例子

      if ($route !== null) { // a route was found
          $route->dispatch();
      }
      else if ($route === null) {
          $this->showErrorPage(404);
      }
      
      $route->doSomething();
      

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 2014-01-27
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        • 2010-12-26
        • 1970-01-01
        • 1970-01-01
        • 2018-08-26
        相关资源
        最近更新 更多