Consolidate Duplicate Conditional Fragments
Move code that is executed in all branches of a conditional outside of it.
“The same fragment of code is in all branches of a conditional expression.”
Don’t repeat yourself.
graph LR
A[If/Else with repeated code] -->|Refactoring| B[Code moved out of If/Else]
When to apply (Smells)
- Duplication: Same line of code at the end (or start) of both
ifandelseblocks.
Motivation
- DRY: Don’t Repeat Yourself.
Mechanics (Steps)
- Identify the duplicate code.
- Move it outside the conditional.
Explanation
Problem
total = price * 0.9; send(); vs total = price * 0.95; send();
Solution
Calculate total inside conditional, call send() after.
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After