November 26, 20269 minutes
A 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.
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.
Here’s the checkout. It starts from the subtotal, gives members a tenth off at fifty or more, and returns the total.
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.
class InvoicePrinter {
String totalLine(Order order) {
double total = order.subtotal();
if (order.customer().isMember() && total > 50) {
total = total - total * 0.10;
}
return "Total: " + total;
}
}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.)
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.
add and sum.// same as Checkout is a copy confessing.50 or for a method
name; the hits show you where the copies live.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 depends on where the copies live.
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.
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.
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.
// 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.
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.
Duplication also hides between siblings. Here, a CSV report and an HTML report both sort the sales the same way.
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;
}
}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.
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();
}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 in a small form. There is a full lesson on it.
Duplicate code is a common cause of 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. So the question isn’t whether two pieces look alike. It’s whether they change for the same reason.
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.
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?
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.
Checklist:
Say it once. Fix it once.