douguai4653 2013-04-16 23:59
浏览 13
已采纳

编码样式 - 如何格式化long if条件以使其可读

I have a long if condition as follows. There are two conditions that both have to not be met, for the statement to evaluate. I did have it as a one liner with a lot of && and ! but it became unreadable. I have tried splitting it into an if elsif else, which is more readable but doesn't read well, as the first if elsif blocks have no code in them.

What would be the best practice to tidy this code 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);
}
  • 写回答

5条回答 默认 最新

  • dongxing2030 2013-04-17 00:17
    关注

    You can use "extract method" refactoring. Replace your conditions to new methods.

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

    In new methods put every compare to separate line.

    P.S. Don't be afraid of long name of methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 如何在不能联网影子模式下的电脑解决usb锁
  • ¥20 服务器redhat5.8网络问题
  • ¥15 如何利用c++ MFC绘制复杂网络多层图
  • ¥20 要做柴油机燃烧室优化 需要保持压缩比不变 请问怎么用AVL fire ESE软件里面的 compensation volume 来使用补偿体积来保持压缩比不变
  • ¥15 python螺旋图像
  • ¥15 算能的sail库的运用
  • ¥15 'Content-Type': 'application/x-www-form-urlencoded' 请教 这种post请求参数,该如何填写??重点是下面那个冒号啊
  • ¥15 找代写python里的jango设计在线书店
  • ¥15 请教如何关于Msg文件解析
  • ¥200 sqlite3数据库设置用户名和密码