Patterncore
Duplicated Code
Also called duplicate code, code clone, copy and paste code.
A code smell: the same logic appears in more than one place, so a change to the rule must be made in each copy, and a copy that is missed becomes a bug.
- Family
- code-smell
- Intent
- Find the places where one rule is written more than once, and give the rule one home that all the places use.
- Refactorings
- Extract function, Slide statements, Pull up method
Intent
Find the places where one rule of the program is written more than once, and give the rule one home. Then each change to the rule is made in one place, and no copy can be left behind.
Problem
Copy and paste is the fastest way to make a second function that works like the first. The cost comes later. The Wikipedia article on duplicate code states it: "if it needs updating, there is a risk that only some of the duplicates will be updated, leaving the others as-is." It adds that a security fault copied into two places stays in the second copy after the first is fixed.1
The forces are these:
- Two copies are often not identical. One has a changed name, an added check or a different constant. The reader must compare them line by line to find what is the same and what is different, and the difference is often the most important part.
- Hunt and Thomas state the principle that the smell breaks, under the name "Don't repeat yourself" (DRY): "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system".2 The unit is a piece of knowledge, not a line of text.
- Kent Beck lists "no duplication" as the third of his four rules of simple design, after "passes the tests" and "reveals intention". Fowler gives the rules in priority order.3
- Not all repeated text is duplication. Two functions can look alike at one point in time and still have different reasons to change. If they are merged, a later change to one of them forces a parameter or a flag into the shared code.
Refactoring puts Duplicated Code first in the list of smells of the first edition, and second, after Mysterious Name, in the second edition.45
Solution
The fix is to give the shared logic a name, and to call it from each place. Refactoring names the steps by where the copies are.5
- Two copies in the same class or module: Extract Function on one copy, then replace the other copy with a call.
- Copies that are similar, but with the statements in a different order: Slide Statements first, so that the similar statements are next to each other. Then extract them.
- Copies in sibling subclasses: extract the function in each, then Pull Up Method to move it to the superclass.
The catalogue at refactoring.com has a card for each of these refactorings.6 In each case the tests that passed before the change must pass after it, because the behaviour does not change.
When should the copies be merged? The rule of three, "Three strikes and you refactor", says that two copies can stay, and that a third copy is the time to extract. Wikipedia attributes it to Don Roberts and says that Fowler made it known through Refactoring.7 The reason is that two cases are often too few to see which parts are the same rule and which parts only look alike.
Example
Two functions compute the price of shipping. Each one adds up the weight of the items and rounds it up to whole kilograms. Only the base price and the price for each kilogram are different.
import assert from "node:assert/strict";
// Before: the weight rule is written twice.
function domesticBefore(items) {
let weight = 0;
for (const item of items) weight += item.kg * item.qty;
return 5 + Math.ceil(weight) * 2;
}
function internationalBefore(items) {
let weight = 0;
for (const item of items) weight += item.kg * item.qty;
return 20 + Math.ceil(weight) * 6;
}
// After: the weight rule has one home.
function billableKg(items) {
let weight = 0;
for (const item of items) weight += item.kg * item.qty;
return Math.ceil(weight);
}
const domestic = (items) => 5 + billableKg(items) * 2;
const international = (items) => 20 + billableKg(items) * 6;
const items = [{ kg: 0.4, qty: 3 }, { kg: 1.1, qty: 1 }];
for (const [name, dom, intl] of [
["before", domesticBefore, internationalBefore],
["after", domestic, international],
]) {
assert.equal(dom(items), 11);
assert.equal(intl(items), 38);
assert.equal(dom([]), 5);
console.log(`${name}: tests pass`);
}
before: tests pass
after: tests pass
The items weigh 2.3 kg, which rounds up to 3, so the domestic price is 5 + 3 × 2 = 11 and the international price is 20 + 3 × 6 = 38. If the rule changes, for example to round to the next half kilogram, the "after" version changes in one function. The "before" version changes in two, and a test that covers only the domestic price does not show that the international one was missed.
| Language | What the example shows |
|---|---|
| JavaScript | the extract above, with node:assert |
| Python | the same extract, with math.ceil and sum over a generator |
| Java | the extract as a private static method, with a record for the item |
| Go | the extract as an unexported function over a slice of structs |
import math
# Before: the weight rule is written twice.
def domestic_before(items):
weight = 0
for item in items:
weight += item["kg"] * item["qty"]
return 5 + math.ceil(weight) * 2
def international_before(items):
weight = 0
for item in items:
weight += item["kg"] * item["qty"]
return 20 + math.ceil(weight) * 6
# After: the weight rule has one home.
def billable_kg(items):
return math.ceil(sum(item["kg"] * item["qty"] for item in items))
def domestic(items):
return 5 + billable_kg(items) * 2
def international(items):
return 20 + billable_kg(items) * 6
items = [{"kg": 0.4, "qty": 3}, {"kg": 1.1, "qty": 1}]
for name, dom, intl in [
("before", domestic_before, international_before),
("after", domestic, international),
]:
assert dom(items) == 11
assert intl(items) == 38
assert dom([]) == 5
print(f"{name}: tests pass")
before: tests pass
after: tests pass
math.ceilreturns anint, so the prices are whole numbers and the asserts compare them with==.- The extracted function uses
sumover a generator. The extract is also the place to make the rule shorter, because there is now one copy to change.
import java.util.List;
public class Main {
record Item(double kg, int qty) {}
// Before: the weight rule is written twice.
static long domesticBefore(List<Item> items) {
double weight = 0;
for (Item item : items) weight += item.kg() * item.qty();
return 5 + (long) Math.ceil(weight) * 2;
}
static long internationalBefore(List<Item> items) {
double weight = 0;
for (Item item : items) weight += item.kg() * item.qty();
return 20 + (long) Math.ceil(weight) * 6;
}
// After: the weight rule has one home.
private static long billableKg(List<Item> items) {
double weight = 0;
for (Item item : items) weight += item.kg() * item.qty();
return (long) Math.ceil(weight);
}
static long domestic(List<Item> items) { return 5 + billableKg(items) * 2; }
static long international(List<Item> items) { return 20 + billableKg(items) * 6; }
interface Price { long of(List<Item> items); }
static void check(String name, Price dom, Price intl) {
List<Item> items = List.of(new Item(0.4, 3), new Item(1.1, 1));
if (dom.of(items) != 11 || intl.of(items) != 38 || dom.of(List.of()) != 5) {
throw new AssertionError(name);
}
System.out.println(name + ": tests pass");
}
public static void main(String[] args) {
check("before", Main::domesticBefore, Main::internationalBefore);
check("after", Main::domestic, Main::international);
}
}
before: tests pass
after: tests pass
Math.ceilreturns adouble, so each version casts the result tolong. In the "before" version the cast is written twice, and a fix to it must be made twice.- The extracted method is
private. The callers keep their public names, so no code outside the class changes. - The test throws
AssertionErroritself, because theassertstatement is off unless the JVM runs with-ea.
package main
import (
"fmt"
"math"
)
type item struct {
kg float64
qty int
}
// Before: the weight rule is written twice.
func domesticBefore(items []item) int {
weight := 0.0
for _, it := range items {
weight += it.kg * float64(it.qty)
}
return 5 + int(math.Ceil(weight))*2
}
func internationalBefore(items []item) int {
weight := 0.0
for _, it := range items {
weight += it.kg * float64(it.qty)
}
return 20 + int(math.Ceil(weight))*6
}
// After: the weight rule has one home.
func billableKg(items []item) int {
weight := 0.0
for _, it := range items {
weight += it.kg * float64(it.qty)
}
return int(math.Ceil(weight))
}
func domestic(items []item) int { return 5 + billableKg(items)*2 }
func international(items []item) int { return 20 + billableKg(items)*6 }
func main() {
items := []item{{0.4, 3}, {1.1, 1}}
for _, v := range []struct {
name string
dom, intl func([]item) int
}{
{"before", domesticBefore, internationalBefore},
{"after", domestic, international},
} {
if v.dom(items) != 11 || v.intl(items) != 38 || v.dom(nil) != 5 {
panic(v.name)
}
fmt.Println(v.name + ": tests pass")
}
}
before: tests pass
after: tests pass
- Go has no implicit conversion from
inttofloat64, sofloat64(it.qty)appears in each copy of the loop. The extract puts the conversion in one place. billableKgstarts with a lowercase letter, so it is not exported. The extract does not change the API of the package.
Consequences
Removing duplication has a cost. Each extract adds a name and a call, and the reader of a caller must go to the shared function to see the rule. That is a good trade when the name says what the rule is.
The wrong merge costs more than the copies. Sandi Metz describes the path: a second caller needs a slightly different behaviour, so a programmer adds a parameter and a conditional to the shared code, and the next programmer adds another. Her summary is "duplication is far cheaper than the wrong abstraction", and her advice is "prefer duplication over the wrong abstraction".8 The Wikipedia article on DRY lists this view as AHA, "avoid hasty abstractions", and lists WET, "write everything twice", as the name for the opposing view.2
Tools find copies of text, not copies of knowledge. PMD's Copy/Paste Detector (CPD) works on many languages, including Java, C, C++, C#, Go, Kotlin and Swift, and its required option --minimum-tokens sets the shortest run of tokens that it reports.9 Pylint reports duplicate-code (R0801) for similar lines in more than one file, with min-similarity-lines at 4 by default.1011 In golangci-lint, the linter dupl reports duplicate fragments, with a default threshold of 150 tokens.12 Two functions that compute the same tax with different code are not found by these tools, and two pieces of boilerplate that the tool reports may not be worth a merge.
How to fix it
- The same lines in one module: Extract Function, and call the result from each place.5
- Similar lines in a different order: Slide Statements to line them up, then extract.5
- The same method in two subclasses: Pull Up Method after the bodies are made the same.5
- The same steps with a different part in the middle: pass the part that differs as a function, with Higher-order function, or use the Template Method.
- A merge that went wrong: Metz gives three steps. Inline the shared code back into each caller, keep in each caller only the part it uses, and delete the rest. Then look for the real duplication again.8
Variants and related patterns
Copy and paste programming. The habit that makes the smell. See Copy and paste programming.
Shotgun Surgery. One change that needs edits in many places. Duplicated Code is one cause: each copy is one more place to edit. See Shotgun Surgery.
Repeated Switches. The same switch on the same type code in many functions is a duplication of the list of cases. See Repeated Switches.
Parallel inheritance hierarchies. The Beck design rules warn of "hidden duplication like parallel class hierarchies", where each subclass in one tree needs a matching subclass in another.3
Data duplication. The same fact stored in two tables, or in a cache and its source, is the DRY problem in data. Database normalization is the fix there. See Data normalization.
References
- Wikipedia, Duplicate code, revision 1374474142, the introduction and Cost
- Wikipedia, Don't repeat yourself, revision 1379490532, the introduction, WET and AHA
- Martin Fowler, Beck Design Rules, bliki, the four rules and their order
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Duplicated Code
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Duplicated Code
- Martin Fowler, Catalog of Refactorings, the cards Extract Function, Slide Statements and Pull Up Method
- Wikipedia, Rule of three (computer programming), revision 1173684754, the introduction
- Sandi Metz, The Wrong Abstraction, 20 January 2016, the story of programmer B and the three steps to go back
- PMD documentation, Finding duplicated code with CPD, the introduction and the option --minimum-tokens
- Pylint documentation, duplicate-code / R0801, Description
- Pylint documentation, All configuration options, Similarities checker, --min-similarity-lines (default 4)
- golangci-lint documentation, Linters configuration, dupl, threshold (default 150)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag E53BEZ Edit this page History Report an error Markdown