2013-04-16 23 views
2

我有一个很长的条件如下。有两个条件不能满足,要评估的陈述。我确实把它作为一个有很多& &和!但它变得不可读。我试图将其拆分成if elsif else,它更易读,但读取不好,因为第一个if elsif块中没有代码。编码风格 - 我如何格式化一长条件,使其可读

整理此代码块的最佳做法是什么?

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); 
} 

回答

3

您可以使用“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); 
} 

在新的方法把每一个比较分开的行。

P.S.不要怕方法的长名。

+0

我给了这个+1,但我越想越多,我意识到这只是将臃肿的'if'条件移动到文件的另一部分。它看起来不错,但现在来自未来的程序员必须找到函数声明来找出发生了什么。嗯... – keyboardSmasher

1

就否定条件,并跳过ifelse if部分为两个初始条件没有做任何事情......

if (
    !($instructionObject->instruction=='nesting_grammar' && 
     $instructionObject->match=='>') 
    || !($instructionObject->instruction=='selector' 
     && is_object($this->instructions[$key+1]) 
     && $this->instructions[$key+1]->instruction == 'nesting_grammar' 
     && $this->instructions[$key+1]->match == '>') 
) { 
    $insertOffset += $childDepth; 
    unset($childDepth); 
} 
0

个人,如果我要跨越多个检查我把它放在类似于我如何布置JavaScript对象的线上;

if (
    great big long check line goes in here && 
    another really long ugly check line goes in here too 
) { 
    // Do this code 
} 
else if (
    check 3 && 
    check 4 
) { 
    //Do this code 
} 
1

不能直接回答你的问题,但对于这样的:

if (my_check($instructionObject) || $instructionObject->instruction=='selector' && my_check($this->instructions[$key+1])) { 
} else { 
    $insertOffset += $childDepth; 
    unset($childDepth); 
} 

function my_check($obj) { 
    return is_object($obj) && $obj->instruction == 'nesting_grammar' && $obj->match == '>'; 
} 

- 你基本上是做同样的事情两次,时间去想该功能。

0

将子表达式拉出变量。伪示例:

flibjit = FlibjitManager.FlibjitInstance(this); 
isFrob = 
    (flibjit.Froblocity >= FlibjitManager.FrobThreshold) && 
    (flibjit.Type == FlibjitTypes.Frobby); 

if (isFrob) { 
    // ... 
+0

我喜欢你的方法与建议的变量名! :) – jtheman