Skip to content

Duplicate Code: When the Same Logic Lives in Several Places

How to spot duplicated logic that drifts apart between copies, why it causes real bugs, and which refactorings merge it back into one place.

5 min readCode smellDead weight

Duplicate code is the same piece of logic written out in two or more places. Sometimes the copies match line for line. More often they started identical and slowly diverged: one copy got a bug fix, a new rule or a rounding tweak, and the other did not. The cost is not the extra lines. The cost is that every change to the rule now needs a search across the codebase, and nothing warns you when you miss a copy. Two parts of the system then disagree about what the rule is, and users find out first. In interviews, duplication is often the first smell a reviewer points to in a take-home or live-coding task. Explaining why it matters, and showing that you know when not to merge, sets you apart from candidates who just say DRY.

Signs

How to spot it in a review.

  • Two functions compute the same business value, such as a price, a status or a deadline, with slightly different code.
  • A bug fix or new rule had to be applied in several files, and one of them was missed.
  • Blocks of code that look alike but differ in variable names, operand order or small constants.
  • Sibling classes or modules carry near-identical methods that nobody dares to change together.
  • Tests for the same rule live in several suites and assert different results.

What it looks like

A typical case, in three languages.

// DeskHop: coworking desk bookings. Amounts are in cents.
interface Booking {
  hours: number;
  hourlyRateCents: number;
  memberTier: "basic" | "pro";
  startsAt: Date;
}

// checkout/quote.ts
export function quoteCheckout(b: Booking): number {
  let subtotal = b.hours * b.hourlyRateCents;
  if (b.memberTier === "pro") {
    subtotal = subtotal * 0.85;
  }
  const day = b.startsAt.getDay();
  if (day === 0 || day === 6) {
    subtotal = subtotal * 1.2; // weekend surcharge, added in March
  }
  return Math.floor(subtotal + 0.5);
}

// billing/invoice.ts
export function invoiceLineCents(b: Booking): number {
  let total = b.hourlyRateCents * b.hours;
  if (b.memberTier === "pro") {
    total -= total * 0.15;
  }
  return Math.floor(total + 0.5);
}

Both functions price the same booking, but they were written by different teams and look different enough that nobody linked them. When the weekend surcharge was added, only checkout got it. A pro member booking 4 hours at 1500 cents on a Saturday is quoted 6120 cents and invoiced 5100. The fix is to extract one bookingPriceCents function, move it next to Booking, and have checkout and billing both call it.

Why it happens

How code ends up like this.

  • Copy-paste is the fastest way to ship a feature that resembles an existing one, and the shortcut is rarely revisited.
  • Different people or teams solve the same problem independently, without knowing the logic already exists.
  • The copies are written in different styles, so search and review do not reveal that they encode the same rule.
  • Fear of touching shared code pushes developers to fork it locally instead of changing it for everyone.

Treatment

The refactorings that cure it, and when to choose each.

Payoff

What you get once it's gone.

  • A business rule changes in exactly one place, so copies cannot disagree.
  • Less code to read, test and review.
  • Bugs fixed once stay fixed everywhere.
  • A named function documents the rule better than scattered inline arithmetic.

When to leave it

Sometimes it's not worth fixing.

  • The code looks the same but represents different decisions that will change for different reasons, such as checkout and payroll rounding that coincide today. Merging them couples two rules.
  • There are only two short copies and the shared abstraction would need flags or many parameters to fit both. Wait for a third occurrence.
  • The copies live in separately deployed services owned by different teams, where a shared library would cost more in versioning than the duplication does.

Common questions

Short answers to the usual doubts.

Is all duplicate code bad?

No. Duplication is harmful when the copies represent the same piece of knowledge, so a change to one must be a change to all. Code that only looks alike by coincidence is fine to keep apart. Ask whether the copies would always change together; if not, leave them.

How do I explain the cost of duplication in an interview?

Point to drift, not line count. Say that every copy is a place a future change can be missed, and give a concrete failure, such as a quote and an invoice computing different totals for the same booking. Then show the extract-and-move fix and mention when you would not merge.

What is the rule of three?

A heuristic: tolerate a second copy, refactor when the third appears. By then you have enough examples to see which parts are truly shared and which vary, so the abstraction fits instead of guessing.

How do I refactor duplicated code safely?

Write characterization tests that pin the current output of each copy first. If the copies disagree, decide which behaviour is correct before merging, because merging will change one caller's results. Then extract, switch callers one at a time, and run the tests after each step.

Can removing duplication make code worse?

Yes. Forcing different cases through one function often adds boolean flags and branches, which is harder to follow than two plain copies. If the shared function grows a flag argument per caller, the merge was probably wrong and inlining it back is a valid fix.

Next guide2 of 6 · Smells: dead weightDead Code: Unused Functions, Branches and FlagsRead the next one