php - 编码风格 - 如何格式化长 if 条件以使其可读

标签 php coding-style

我有一个很长的 if 条件,如下所示。为了对语句求值,有两个条件必须同时满足。我确实把它作为一个内衬,里面有很多&&和!但它变得不可读。我尝试将其拆分为 if elsif else,它更具可读性,但读起来不太好,因为第一个 if elsif block 中没有代码。

整理此代码块的最佳实践是什么?

if ($instructionObject->instruction=='nesting_grammar' && $instructionObject->match=='>'){ //if instruction is a '>' child indicator
   //don't change the child depth
}else if ($instructionObject->instruction=='selector' && is_object($this->instructions[$key+1]) && $this->instructions[$key+1]->instruction == 'nesting_grammar' && $this->instructions[$key+1]->match == '>'){ //if instruction is a selector followed by a '>'
   //don't change the child depth
}else{
   $insertOffset += $childDepth;
   unset($childDepth);
}

最佳答案

您可以使用“extract method”重构。将您的条件替换为新方法。

if ($this->isInstructionNestingGrammar($instructionObject)){ 
   //don't change the child depth
}else if ($this->isIntructionSelect($instructionObject)){ 
   //don't change the child depth
}else{
   $insertOffset += $childDepth;
   unset($childDepth);
}

在新方法中,将每个比较放在单独的行中。

附注不要害怕方法名称太长。

关于php - 编码风格 - 如何格式化长 if 条件以使其可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16049220/

相关文章:

php - Wordpress - 如何在 woocommerce 中使运费为零?

c# - 在条件运算中使用 true 和 false 作为表达式

python - Python 中的参数、局部变量和全局变量编码约定

c++ - 如何简化这个 typedef 不同的 switch 语句?

java - 从 php exec 或 shell_exec 运行 java jar 不适用于蜡染

php - 从处理程序获取图像大小

php - 博客文章的单独页面

php - 使用Google Spreadsheet API获取通过过滤器 View 过滤的值

Scala lambda 样式 (x) => {...} 与 { (x) => ... }

android - 在带有边框的 textView 中创建自定义 UI 组件按钮