在if / else语句顺序的最佳实践语句、顺序、if、else

2023-09-02 11:58:45 作者:魁

这是一个更好的做法? (我编码在.net,如果有差别)

 如果条件= true,那么
   ...真正的行动 - 即使罕见...
其他
   ...行动
END IF
 

 如果条件= [最常见的条件] THEN
   ......最常见的动作....
其他
   ...至少有共同行动
END IF
 

解决方案

据史蒂夫·麦康奈尔,作者的 code完成的,你应该

  

把情况下,你通常希望   第一个进程。这与线   的投入code的一般原则   从决策结果尽可能接近   尽可能地决定... [放   之后,正常情况下,如果的]放   着眼于阅读主要流而   不是通过特殊的涉水   的情况下,因此code是更容易阅读   整体。

第一篇Java基础知识 复习博客

code完全,第二版,页356-357。

Which is a better practice? (I'm coding in .Net if that makes a difference)

IF condition = true THEN
   ...true action--even if rare...
ELSE
   ...action
END IF

or

IF condition = [most common condition] THEN
   ...most common action....
ELSE
   ...least common action
END IF

解决方案

According to Steve McConnell, author of Code Complete, you should

"Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision...[putting the normal case after the if] puts the focus on reading the main flow rather than on wading through the exceptional cases, so the code is easier to read overall."

Code Complete, 2nd Edition, pages 356-357.