Course contentsShow
← Software Engineering
Lesson 356 of 1,93310. RefactoringFree lesson

Consolidate Duplicate Conditional Fragments

Remove code duplication by moving identical statements out of conditional branches to a single location.

Consolidate Duplicate Conditional Fragments

What you'll learn: How to eliminate repetitive code that appears in multiple branches of the same conditional statement.

The Problem

Sometimes when writing conditionals, you'll find yourself copying the same line of code into every branch—whether it's if, else if, or else. This duplication is easy to miss but creates maintenance headaches: if you need to change that repeated statement, you must remember to update it in every branch.

Analogy: Imagine a restaurant where every waiter ends each order—regardless of what the customer chose—by saying "Enjoy your meal!" There's no reason for that phrase to be written separately in the burger protocol, the salad protocol, and the soup protocol. It should appear once, after the order handling is complete.

The Solution

Move identical statements out of all conditional branches to a single location—either before the conditional (if the statement should run first) or after it (if it should run last). This way, the code executes exactly once, in one place.

Before refactoring:

if (isSpecialOrder) {
    price = calculateSpecialPrice();
    sendReceipt();
} else {
    price = calculateRegularPrice();
    sendReceipt();
}

After refactoring:

if (isSpecialOrder) {
    price = calculateSpecialPrice();
} else {
    price = calculateRegularPrice();
}
sendReceipt();

Notice sendReceipt() now appears once, after the conditional. Both branches still execute it, but there's no duplication.

Why It Matters

This refactoring reduces the risk of inconsistent updates, makes the code's true intent clearer (the conditional is only about pricing), and makes future changes safer and simpler.

Key Takeaway: When identical code appears in all branches of a conditional, move it outside the conditional to eliminate duplication and improve maintainability.