Duplicate Code

The same code structure in multiple places.

“Number one in the stink parade.” – Fowler & Beck

Signs of Use (Symptoms)

  • Copy-pasted blocks.
  • Similar logic with minor variations in multiple places.

Why it is bad (Consequences)

  • Maintenance: Fix a bug in one place, forget the copies.
  • Inconsistency: Copies diverge over time.

Why it happens (Root Cause)

Copy-paste is the fastest way to “reuse” code.

When it might be okay (Exceptions)

  • Very small, trivial expressions (e.g., i++).
  • Tests may intentionally be explicit/repetitive for clarity.

Explanation

Problem

Function A and Function B have 20 identical lines.

The Flaw

DRY violation. Knowledge exists in two places.

Real world analogy

Two legal contracts with the same clause written out manually in both. If law changes, both must be updated.

Refactoring Solution

  • Extract Method: Create a shared function.
  • Pull Up Method: Move duplicate logic to a base class.
  • Form Template Method: If variations exist.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Fast
  • Bugs multiply
  • Drift
  • Comparison

    • Related Antipatterns: Data Clumps.
    • Related Principles: DRY.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)