Course contentsShow
← Computer Science
Lesson 2327 of 2,87252. Clean Code and RefactoringFree lesson

Remove Duplicate Code: DRY Principle in Practice

Learn strategies to identify and eliminate code duplication through extraction and parameterization.

Remove Duplicate Code: DRY Principle in Practice

What you'll learn: How to systematically identify and eliminate duplicated code through extraction and parameterization techniques.

The Core Idea

The DRY (Don't Repeat Yourself) principle states that every piece of knowledge should have a single, authoritative representation in your codebase. When you copy-paste code or write similar logic multiple times, you create maintenance nightmares—fixing a bug means hunting down every duplicate, and changes must be synchronized everywhere.

Think of duplicate code like having the same phone number written on sticky notes throughout your house. When you change your number, you must find and update every note. One master list would be far more reliable.

Strategies for Eliminating Duplication

1. Extract Method

When identical or nearly-identical code blocks appear, pull them into a single function. You've learned this technique—now apply it specifically to duplicates.

2. Parameterization

Similar code that differs only in values can be unified by accepting those values as parameters:

# Before: Duplication
def calculate_discount_bronze():
    return price * 0.05

def calculate_discount_silver():
    return price * 0.10

# After: Parameterized
def calculate_discount(tier_multiplier):
    return price * tier_multiplier

3. Extract Variable

When complex expressions repeat, extract them once and reuse the result.

4. Consolidate Similar Logic

Look for patterns where logic differs slightly but follows the same structure—these are prime candidates for abstraction through conditionals or strategy patterns.

Identifying Duplication

  • Look for copy-pasted blocks
  • Search for similar function/method names with variations
  • Notice patterns where you're writing "almost the same thing again"
  • Use code review to spot structural similarities

Key Takeaway: Duplicate code multiplies maintenance effort; eliminate it by extracting shared logic into single, parameterized abstractions that serve as the one source of truth.