gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:07:35 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com