这一章依然比较简单。条件语句主要有两类,if-else,和switch-case。
总体的原则都是要提高可读性,降低犯错率,提高效率等。
if-else
对于if-else语句来说,要注意的有这么几条:
- 一、先写正常情况下会发生的条件,这样读的人一看就知道正常情况下会怎么样,可以很容易的知道这段代码的功能,同时执行效率也会提高,因为正常的情况会是最可能发生的情况。
- 二、把正常的情况放在if后面而不是else后面。这样流程会清晰很多。
- 三、用了if就要考虑要不要用else,如果不用最好注释。
- 四、考虑是否要交换if和else的内容。
- 五、很复杂的条件检测最好用一个布尔函数来调用。太复杂的条件会让读者很难捕捉到你这个判断到底在判断什么。
- 六、保证所有的情况都要覆盖到。条件嵌套多了的时候很可能会漏掉某些情况的处理。
- 七、考虑是否可以用case语句来实现。
switch-case
对于switch-case语句来说,要注意的也有几条:
- 一、case的顺序。这个是最常用的问题,一般来说把使用频率最高的,正常的case放在前面,符合人的阅读习惯。如果各个case的地位都是平等的,那么可以考虑要字母顺序等。
- 二、每个case里的语句尽量简短,不要一个case写一页,太多了就改成函数。
- 三、用default的case去检查错误的情况,正常流程不应该跑到default里去。不要default里还包括一个正常的case,那样很容易搞混,尤其要修改的时候,读代码的人可能根本不知道是这样的。
- 四、像C++中如果不break这个case执行完会执行下一个,要格外小心。如果真的是想用这种特性,一定要注释,一般不提倡这样用。
好了,这一章就这些内容。同样附上checklist:
Checklist: Using Conditionals
if-then Statements
- Is the nominal path through the code clear?
- Do if-then tests branch correctly on equality?
- Is the else clause present and documented?
- Is the else clause correct?
- Are the if and else clauses used correctly-not reversed?
- Does the normal case follow the if rather than the else?
if-then-else-if Chains
- Are complicated tests encapsulated in boolean function calls?
- Are the most common cases tested first?
- Are all cases covered?
- Is the if-then-else-if chain the best implementation-better than a case statement?
case Statements
- Are cases ordered meaningfully?
- Are the actions for each case simple-calling other routines if necessary?
- Does the case statement test a real variable, not a phony one that's made up solely to use and abuse the case statement?
- Is the use of the default clause legitimate?
- Is the default clause used to detect and report unexpected cases?
- In C, C++, or Java, does the end of each case have a break?