Cover of Code Complete by Steve McConnell - Business and Economics Book

From "Code Complete"

Author: Steve McConnell
Publisher: Pearson Education
Year: 2004
Category: Computers

🎧 Free Preview Complete

You've listened to your free 10-minute preview.
Sign up free to continue listening to the full summary.

🎧 Listen to Summary

Free 10-min Preview
0:00
Speed:
10:00 free remaining
Chapter 4: Statements
Key Insight 2 from this chapter

Best Practices for 'if' Statements and 'if-else' Chains

Key Insight

When constructing 'if' statements, prioritize readability and maintainability by writing the nominal execution path first, relegating unusual or error cases to secondary positions. This approach ensures the normal flow is immediately apparent, aiding understanding and sometimes performance. It is critical to branch correctly on equality conditions, for example, using '>' instead of '>=' or '<' instead of '<=' can lead to off-by-one errors; always consider the equals case. The expected or normal case should consistently follow the 'if' clause, keeping code resulting from a decision close to the decision itself. Avoid null 'if' clauses, which involve empty statements after the 'if' condition; these can always be improved by negating the predicate and moving the 'else' clause's content directly into the 'if' block, thereby eliminating the unnecessary 'else'.

Always consider the 'else' clause, as a General Motors analysis found that 50 to 80 percent of 'if' statements should logically include one. Even if no action is explicitly required for the 'else' case, coding a null 'else' statement or, at minimum, commenting why it is absent, demonstrates that the alternative path has been considered. It is important to test the 'else' clause for correctness, not just the 'if' clause, and to vigilantly check for accidental reversal of 'if' and 'else' code blocks or backward logic in the 'if' test itself, which are common programming errors.

For chains of 'if-then-else-if' statements, especially those involving complex conditions, simplify readability by encapsulating these tests within boolean function calls (e.g., 'if (IsControl(inputCharacter))'). Arrange cases by frequency, placing the most common conditions first to improve both code efficiency and reader comprehension, as users typically seek common scenarios first. Ensure all possible cases are covered by including a final 'else' clause that contains an error message or assertion, specifically for the developer, to trap unexpected inputs. If the programming language supports more suitable constructs, like 'case' statements, these should be preferred over lengthy 'if-then-else-if' chains for improved clarity and conciseness, especially when dealing with multiple discrete conditions or ranges.

📚 Continue Your Learning Journey — No Payment Required

Access the complete Code Complete summary with audio narration, key takeaways, and actionable insights from Steve McConnell.