# Duplicate CodeA discount rule copied into three classes, a bug fix that reaches two. Learn to spot duplicate code, pick the right refactoring, and tell real duplication from look-alikes.

A member gets a tenth off any order of fifty or more. That rule lives in three places: the
checkout, the invoice, and the mobile app. Then a bug report arrives: orders of exactly fifty are
not getting the discount. Someone fixes it in the checkout, and in the invoice. But the mobile app
still has the old copy. So the same member sees one total on the invoice, and a different total in
the app. That's a smell called **Duplicate Code**: one piece of knowledge, copied into several
places.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="ZpqA069wNpA" title="Duplicate Code" >}}

## One rule, three copies

```mermaid {alt="Before and after. Before, the member discount rule is copied into Checkout, InvoicePrinter and MobileApi, and a bug fix reaches only two of the three copies. After, one MemberDiscount class holds the rule and all three classes ask it." caption="Three copies, or one rule."}
flowchart TB
  subgraph Before
    direction LR
    B1["Checkout<br/>copy of the rule"]
    B2["InvoicePrinter<br/>copy of the rule"]
    B3["MobileApi<br/>copy of the rule (forgotten)"]
  end
  subgraph After
    direction LR
    A1["Checkout"]
    A2["InvoicePrinter"]
    A3["MobileApi"]
    AD["MemberDiscount"]
    A1 --> AD
    A2 --> AD
    A3 --> AD
  end
  Before ~~~ After
  class B1,B2 c5
  class B3 bad
  class AD good
```

## The street map

Picture a printed street map, pinned up in three offices, so that drivers know the way. One day, a
bridge closes. Someone updates the map in two offices, and forgets the third. Now two offices send
drivers the new way, and the third sends them to a closed bridge.

Nobody was careless. The map was simply copied, so every change needed three trips. The map is our
discount rule, and the offices are the checkout, the invoice and the app. The fix is one map, in
one place, that everyone reads.

```mermaid {alt="The street map mapped onto code. The printed map is the discount rule, each office is a class that holds a copy, the closed bridge is the changed rule, and the forgotten office is the class whose copy was never updated." caption="The street map, mapped onto the code."}
flowchart LR
  A["the printed map"] --> A2["the discount rule"]
  B["each office's copy"] --> B2["Checkout, InvoicePrinter, MobileApi"]
  C["the closed bridge"] --> C2["the changed rule"]
  D["the office nobody updated"] --> D2["MobileApi"]
  class D2 bad
```

## What it looks like

Here's the checkout. It starts from the subtotal, gives members a tenth off at fifty or more, and
returns the total.

```java
class Checkout {
    double total(Order order) {
        double total = order.subtotal();
        if (order.customer().isMember() && total > 50) {
            total = total - total * 0.10;
        }
        return total;
    }
}
```

The invoice printer needs the same total for its last line, and the mobile app needs it for its
summary.

```java
class InvoicePrinter {
    String totalLine(Order order) {
        double total = order.subtotal();
        if (order.customer().isMember() && total > 50) {
            total = total - total * 0.10;
        }
        return "Total: " + total;
    }
}
```

```java
class MobileApi {
    OrderDto summary(Order order) {
        double total = order.subtotal();
        if (order.customer().isMember() && total > 50) {
            total = total - total * 0.10;
        }
        return new OrderDto(order.id(), total);
    }
}
```

So the quickest thing is to copy the lines, paste them, and move on. It's fast, and it works. For a
while. Notice that the surroundings differ: the checkout returns a number, the invoice returns
text, and the app builds an object. That's why the copies are easy to miss. Look at the three side
by side, and the discount lines are identical.

(`Order`, `OrderDto` and `Customer` are placeholders, and the rate, the threshold and the totals
are made-up example values.)

## Why it hurts

Now the bug. The rule says fifty or more, but the code says over fifty. The fix is tiny: `>`
becomes `>=`. Someone fixes the checkout. Someone else fixes the invoice. The mobile app is
forgotten. Nothing fails to compile, and no test goes red.

A member with an order of exactly fifty now sees two different totals, depending on where they
look (45.00 on the invoice, 50.00 in the app). That's the real cost of duplication: you don't pay
when you copy, you pay every time the rule changes.

And each copy drifts a little, a rounding here, a rename there, until nobody knows which one is
right. A duplicated bug is worse, because you have to find every copy of the mistake as well.

## How to spot it

- **Nearly identical code.** The [Code Smells Reference](https://refactoring-assistant.github.io/dispensables/duplicate-code)
  suggests looking for snippets that look nearly the same, and notes that a properly configured
  IDE can detect duplicates for you.
- **The same fix, again and again.** The same bug fixed in several commits, or a fix that landed in
  only some of the places.
- **Same job, different names.** Two methods that do the same thing under different names, like
  `add` and `sum`.
- **Comments like "keep in sync".** A comment such as `// same as Checkout` is a copy confessing.
- **A search for a distinctive value.** Search the project for a value like `50` or for a method
  name; the hits show you where the copies live.

## The key insight: one knowledge, one home

Duplication isn't repeated text. It's one piece of knowledge, written down in several places. The
rule about members and fifty is a single decision, and it should have a single home.

This is the **DRY** principle (don't repeat yourself) from *The Pragmatic Programmer* by Andy Hunt
and Dave Thomas: every piece of knowledge should have a single, authoritative place in a system.
Copying isn't a crime when you're sketching; the smell is leaving the copies in place once the idea
is proven.

> **Say it once. Fix it once.**

## The fix: Extract Method, then Extract Class

The fix depends on where the copies live.

```mermaid {alt="Which refactoring? Where do the copies live? In the same class: Extract Method. In sibling subclasses: Pull Up Method if the code is identical, Form Template Method if the steps match but the details differ. In unrelated classes: Extract Class, or Extract Superclass if they can sensibly share a parent." caption="Pick the refactoring by where the copies live."}
flowchart TD
  Q{"where do the<br/>copies live?"}
  Q -->|"same class"| M["Extract Method"]
  Q -->|"sibling<br/>subclasses"| S["identical: Pull Up Method<br/>similar: Form Template Method"]
  Q -->|"unrelated<br/>classes"| C["Extract Class<br/>(Extract Superclass if a<br/>parent makes sense)"]
  class M,S,C good
```

When they sit in the same class, the move is **Extract Method**. Take the discount lines and give
them a name: `discounted`. Now the checkout calls one method.

```java
class Checkout {
    double total(Order order) {
        return discounted(order);
    }

    private double discounted(Order order) {
        double total = order.subtotal();
        if (order.customer().isMember() && total > 50) {
            total = total - total * 0.10;
        }
        return total;
    }
}
```

Make each move in a small step, and run the tests in between. A refactoring should not change what
the code does.

But the invoice printer and the mobile app are different classes, with no shared parent. So the
method moves into a class of its own: **Extract Class**.

```java
class MemberDiscount {
    double apply(Order order) {
        double total = order.subtotal();
        if (order.customer().isMember() && total > 50) {
            total = total - total * 0.10;
        }
        return total;
    }
}
```

`MemberDiscount` holds the rule, once. The checkout, the invoice and the app all ask it.

```java
// Checkout
return discount.apply(order);

// InvoicePrinter
return "Total: " + discount.apply(order);

// MobileApi
return new OrderDto(order.id(), discount.apply(order));
```

If the classes can sensibly share a parent, refactoring.guru lists **Extract Superclass** as another
route. Without a family, Extract Class is the one.

```mermaid {alt="Class diagram after Extract Class. Checkout, InvoicePrinter and MobileApi each use MemberDiscount, which holds the member discount rule." caption="One rule, three callers."}
classDiagram
  class MemberDiscount {
    apply(Order) double
  }
  class Checkout
  class InvoicePrinter
  class MobileApi
  Checkout --> MemberDiscount
  InvoicePrinter --> MemberDiscount
  MobileApi --> MemberDiscount
```

## Replay the bug fix

Now replay the bug fix. One edit, in `MemberDiscount`: `>` becomes `>=`. The checkout, the invoice
and the app all agree, because there is only one rule left to agree with. Search the project for the
rule now, and there's one hit instead of three. There's one set of tests for the rule, instead of
three, and next quarter's change is one edit again.

## A second example: sibling subclasses

Duplication also hides between siblings. Here, a CSV report and an HTML report both sort the sales
the same way.

```java
class CsvReport extends Report {
    String render(List<Sale> sales) {
        List<Sale> sorted = new ArrayList<>(sales);
        sorted.sort(Comparator.comparing(Sale::date));
        String out = "date,amount\n";
        for (Sale s : sorted) {
            out += s.date() + "," + s.amount() + "\n";
        }
        return out;
    }
}
```

```java
class HtmlReport extends Report {
    String render(List<Sale> sales) {
        List<Sale> sorted = new ArrayList<>(sales);
        sorted.sort(Comparator.comparing(Sale::date));
        String out = "<ul>";
        for (Sale s : sorted) {
            out += "<li>" + s.date() + " " + s.amount() + "</li>";
        }
        return out + "</ul>";
    }
}
```

Identical code in sibling subclasses goes up into the parent: **Pull Up Method**. Both reports now
call the parent's sorting, and each one loses its copy. (refactoring.guru lists Pull Up Method as a
step that helps you reach Form Template Method.)

But the loops differ: one writes commas, the other writes list items. The steps match, and the
details don't. When steps match and details differ, use **Form Template Method**: the parent owns
the steps, and each child fills in the details.

```java
abstract class Report {
    String render(List<Sale> sales) {
        List<Sale> sorted = new ArrayList<>(sales);
        sorted.sort(Comparator.comparing(Sale::date));
        StringBuilder out = new StringBuilder(header());
        for (Sale s : sorted) {
            out.append(row(s));
        }
        return out.append(footer()).toString();
    }

    abstract String header();
    abstract String row(Sale s);
    abstract String footer();
}
```

```java
class CsvReport extends Report {
    String header() { return "date,amount\n"; }
    String footer() { return ""; }

    String row(Sale s) {
        return s.date() + "," + s.amount() + "\n";
    }
}
```

That's the [Template Method pattern](/patterns/template-method-pattern/) in a small form. There
is a full lesson on it.

```mermaid {alt="Class diagram after Form Template Method. The abstract Report class owns render and declares header, row and footer. CsvReport and HtmlReport extend Report and fill in header, row and footer." caption="The parent owns the steps."}
classDiagram
  class Report {
    <<abstract>>
    render(List) String
    header() String
    row(Sale) String
    footer() String
  }
  class CsvReport
  class HtmlReport
  Report <|-- CsvReport
  Report <|-- HtmlReport
```

## Shotgun Surgery and Divergent Change

Duplicate code is a common cause of [Shotgun Surgery](/code-smells/shotgun-surgery/): one
change, many places to edit.

And watch for the opposite mistake. Merge two things that change for different reasons, and you
build a class with two masters. That's [Divergent Change](/code-smells/divergent-change/). So
the question isn't whether two pieces look alike. It's whether they change for the same reason.

## Myths, and when to leave it

**Myth: "any similar-looking code is duplication."** Not so. *Incidental duplication* is two pieces
that look alike but change for different reasons. Say free shipping starts at fifty, and the member
discount starts at fifty. Same number, two rules.

```java
boolean freeShipping(double total) {
    return total >= 50;
}

boolean memberDiscount(Order order) {
    return order.customer().isMember()
            && order.subtotal() >= 50;
}
```

Merge them into one constant, and when marketing moves the discount, shipping moves too. So leave
them apart. (Sandi Metz put the same idea as "prefer duplication over the wrong abstraction".)

A useful rule of thumb is the **rule of three**: wait for the third copy, then refactor. Two copies
don't yet show you the pattern. Martin Fowler popularised the rule in *Refactoring*; it is
attributed to Don Roberts.

So when is duplication fine?

- **When it's incidental**: the pieces change for different reasons.
- **In tests**: a little repetition keeps each test readable on its own.
- **In generated code**: you fix the generator, not the output.

```mermaid {alt="Decision flow. Do the copies change for the same reason? If no, leave them apart. If yes, is it generated code? If yes, fix the generator. If no, is it test code where repetition keeps tests readable? If yes, leave it. If no, refactor: Extract Method, Pull Up Method, Form Template Method or Extract Class." caption="Same reason to change, or leave it."}
flowchart TD
  Q1{"same reason<br/>to change?"} -->|no| L["leave them apart"]
  Q1 -->|yes| Q2{"generated code?"}
  Q2 -->|yes| G["fix the generator"]
  Q2 -->|no| Q3{"test code?"}
  Q3 -->|"yes, repetition<br/>reads better"| L
  Q3 -->|no| R["refactor"]
  class R good
  class L,G muted
```

## Recap

Duplicate code is one piece of knowledge, written in several places. Use Extract Method inside a
class, Pull Up Method or Form Template Method between siblings, and Extract Class between unrelated
classes. But only when the copies change for the same reason. Duplication feeds shotgun surgery,
and over-merging feeds divergent change.

```mermaid {alt="Recap chain: one rule with many copies; same class, Extract Method; siblings, Pull Up Method or Form Template Method; unrelated, Extract Class." caption="Say it once. Fix it once."}
flowchart LR
  A["one rule,<br/>many copies"] --> B["same class:<br/>Extract Method"] --> C["siblings: Pull Up,<br/>Form Template"] --> D["unrelated:<br/>Extract Class"]
  class D good
```

Checklist:

- Do two pieces of code look nearly identical, or do two methods do the same job?
- Was a fix applied in only some of the places?
- Do the copies change for the same reason? If not, leave them apart.
- Same class, siblings or unrelated classes? Pick the refactoring by where the copies live.
- Is it the third copy yet?

> **Say it once. Fix it once.**

## Further reading

- Code Smells Reference: [Duplicate Code](https://refactoring-assistant.github.io/dispensables/duplicate-code).
- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, "Duplicated Code".
- Refactoring catalog: [Extract Function](https://refactoring.com/catalog/extractFunction.html)
  (Extract Method), [Extract Class](https://refactoring.com/catalog/extractClass.html),
  [Pull Up Method](https://refactoring.com/catalog/pullUpMethod.html).
- refactoring.guru: [Duplicate Code](https://refactoring.guru/smells/duplicate-code),
  [Form Template Method](https://refactoring.guru/form-template-method).
- Andy Hunt and Dave Thomas, *The Pragmatic Programmer* (DRY); [Don't repeat yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
- [Rule of three (computer programming)](https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)).
