From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewConsolidate Conditional Expression
Key Insight
Often, code contains a series of conditional checks where each condition is distinct, yet all of them lead to the identical resulting action. This pattern, while functionally correct, can mislead readers into perceiving a sequence of separate, independent evaluations rather than a single, unified condition. The code effectively performs the same action across multiple paths, making the true intent ambiguous.
Consolidating these conditional checks into a single expression clarifies the code's intention by explicitly demonstrating that a group of individual checks collectively forms one overarching condition for a specific outcome. This refactoring makes it evident that the various checks are logically related and are all precursors to the same action. A significant benefit of this consolidation is that it frequently sets up the code for a subsequent Extract Function refactoring, enabling the replacement of a detailed 'what' with a clear 'why'. However, this refactoring should be avoided if the checks are truly independent and should not be conceptually combined.
The process begins by ensuring that none of the individual conditional statements have side effects; if they do, a 'Separate Query from Modifier' refactoring should be applied first. Then, two conditional statements are combined using appropriate logical operators: `or` for sequential conditions and `and` for nested `if` statements. This step is repeated, with testing after each combination, until all relevant conditionals are integrated into a single expression. For example, `if (anEmployee.seniority < 2) return 0; if (anEmployee.monthsDisabled > 12) return 0; if (anEmployee.isPartTime) return 0;` becomes `if ((anEmployee.seniority < 2) || (anEmployee.monthsDisabled > 12) || (anEmployee.isPartTime)) return 0;`. This consolidated condition can then be extracted into a descriptive function like `isNotEligableForDisability()`.
📚 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.