我有一个很长的 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/