在if / else语句顺序的最佳实践 [英] Best Practice on IF/ELSE Statement Order

查看:120
本文介绍了在if / else语句顺序的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

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

  

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

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.

这篇关于在if / else语句顺序的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆