|
An expression of form a ? b : c should only be used to produce a value that the program uses. |
Do not use an if-statement with an empty statement preceding else [EMPTY-THEN]
Instead of
if(x > 0) { } else { doSomething(); }write if(x <= 0) { doSomething(); } |
Do not use conditions that are always true or always false [CONSTANT-CONDITION]
Do not use an if-statement whose condition
is always true or always false, except strictly
for debugging or code-checking purposes. For example, if
at a particular place it is not possible for
i and k to have the same value, then
do not say
if(i == k) { ... } |
Do not use redundant tests in if-statements [REDUNDANT-TEST]
The else part of an if-statement is done if the
condition being tested is false. Do not test
whether it is false. For example,
if(x > 0) { step1(); } else if(x <= 0) { step2(); }should be replaced by if(x > 0) { step1(); } else { step2(); } |
If code is only performed by one branch of an if-statement, then it must be written inside that branch [BRANCH]
Look at the following function definition.
int demo(int x) { int y; if(x > 0) { y = x + 1; } else { return -x; } return y; }Notice that statement return y can only be performed when x > 0. Moving it into the if-statement yields int demo(int x) { int y; if(x > 0) { y = x + 1; return y; } else { return -x; } }A better form is int demo(int x) { if(x > 0) { return x + 1; } else { return -x; } } |
Each case in a switch-statement must logically end on a break statement or a return statement. (That means the case body must either perform a break or a return in all cases, not that the break or return must physically be the last statement.) You cannot let one case fall into the next. However, you are allowed to have multiple case labels that share a single block of code. |
|