Cover of Refactoring by Martin Fowler, Kent Beck - Business and Economics Book

From "Refactoring"

Author: Martin Fowler, Kent Beck
Publisher: Addison-Wesley Professional
Year: 1999
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 10: Simplifying Conditional Logic
Key Insight 3 from this chapter

Replace Nested Conditional with Guard Clauses

Key Insight

Conditional expressions often serve two distinct purposes: handling two equally 'normal' behaviors (requiring an if-else structure) or addressing an unusual condition that warrants an early exit from a function, leaving the main logic to proceed unimpeded. When nested conditionals are used for the latter, they obscure the code's true intention by assigning equal structural weight to both the normal and exceptional paths, making the core functionality harder to discern.

A guard clause is a more appropriate construct for unusual conditions. It operates by checking for an exceptional state and, if found, immediately exiting the function (e.g., with a `return` statement). This design clearly communicates that the guarded condition is not part of the function's primary flow, allowing the normal, main processing logic to exist without indentation or intertwining with the 'get out' conditions. This approach prioritizes clarity, advocating for multiple exit points if it makes the method more understandable, rather than rigidly adhering to a single-exit-point rule.

Mechanically, this refactoring involves selecting an outermost conditional that represents an unusual condition and transforming it into a guard clause. This process is applied iteratively, with testing after each change. If multiple guard clauses result in the same outcome, they can be consolidated using 'Consolidate Conditional Expression'. For instance, a nested payment calculation checking for `employee.isSeparated` and `employee.isRetired` can be refactored from nested `if-else` statements to: `if (employee.isSeparated) return {amount: 0, reasonCode: 'SEP'}; if (employee.isRetired) return {amount: 0, reasonCode: 'RET'}; // main logic`. Similarly, `adjustedCapital` calculations can be simplified by reversing conditions like `anInstrument.capital > 0` to `anInstrument.capital <= 0` to enable early returns for invalid inputs.

📚 Continue Your Learning Journey — No Payment Required

Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.