|
Do not use a ? b : c as a statement [Conditional expression as statement: 1-4 points]
An expression of form a ? b : c should only be used to produce a value that the program uses. |
Do not write an explicit empty else [Empty else: 1-2 points]
Instead of
if(x > 0) { doSomething(); } else { }write if(x > 0) { doSomething(); } |
Do not use an if-statement with an empty statement preceding else [Empty then: 1-2 points]
Instead of
if(x > 0) { } else { doSomething(); }write if(x <= 0) { doSomething(); } A loop body should not have the form if(...) { continue; } else { ... }Statement continue; says to do the next iteration of the loop. But that is what the program would normally do at the end of the loop body. |
Do not force a boolean expression to be a test where that is not appropriate. [Boolean force: 1 point]
Suppose that E is an expression of type bool. Statement
if(E) { return true; } else { return false; }is equivalent to return E.If it is appropriate to treat a boolean expression in a way similarly to an arithmetic expression (as a value), then do so. It yields simpler and more efficient programs. |
Do not use conditions that are always true or always false [Constant condition: 1-2 points]
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: 1-2 points]
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 separation: 1 point]
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. |
|