Consolidate Conditional Expression
Combine checks that lead to the same result.
“You have a sequence of conditional tests with the same result.”
Combine them with AND or OR.
graph LR
A[Multipe Ifs returning same Value] -->|Refactoring| B[Single If Combining Checks]
When to apply (Smells)
- Duplicate Logic: Different checks return
0orfalse.
Motivation
- Readability: Shows that these checks are variation of the same underlying rule.
- Enables Extract Method on the condition.
Mechanics (Steps)
- Combine the conditionals using
&&or||. - (Optional) Extract the combined condition into a method.
Explanation
Problem
Multiple checks, all return the same thing.
if (x < 0) return 0; if (y > 10) return 0;
Solution
if (x < 0 || y > 10) return 0;
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After