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 1 from this chapter

Decompose Conditional

Key Insight

Complex conditional logic is a significant source of program complexity, especially in long functions. While function length itself can hinder readability, conditional statements exacerbate this issue by obscuring the 'why' behind actions, even when the 'what' is clear. This makes the code harder to understand and maintain, as the underlying intention of the branching logic is not immediately apparent.

To address this, a common refactoring technique involves decomposing complex conditional sections. This means breaking down large blocks of conditional code, including both the condition checks and their corresponding actions, into smaller, more focused functions. Each new function is named to clearly express its intention, highlighting both the condition being branched upon and the reason for that specific branching. This approach is a particular and highly valuable application of the Extract Function technique, significantly enhancing code clarity by revealing intent.

The mechanics involve applying Extract Function separately to the conditional expression itself and to each 'leg' (the 'then' and 'else' blocks) of the conditional statement. For example, a charge calculation `if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd)) charge = quantity * plan.summerRate; else charge = quantity * plan.regularRate + plan.regularServiceCharge;` is refactored by extracting the condition into `summer()`, the 'then' leg into `summerCharge()`, and the 'else' leg into `regularCharge()`. This results in a much clearer `charge = summer() ? summerCharge() : regularCharge();`.

📚 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.