The price of Raka's T-shirt goes up from $75 to $80. How many places do you have to change? If the price is written in the Instagram catalogue, the shop page and the receipt, the answer is three, and the third one is easy to forget. The buyer sees $80, the receipt says $75. Nobody complains right then, but the numbers no longer match.
The DRY principle (Don't Repeat Yourself) prevents that problem: every piece of knowledge in a program has one place. Knowledge here means a rule the program uses, such as the price of a T-shirt or the way to write a price. So what counts as repetition isn't text that looks alike, but the same rule.
A receipt with three formatters
A formatter is code that turns a number into price text. Here is the receipt code of Raka's T-Shirt Shop for cart A (2 plain tees, 1 printed tee, voucher SAVE10). printReceipt takes the cart, the amount saved and the total, then prints the receipt:
function itemLine(item) {
return item.name + ' x' + item.qty + ': $' + (item.price * item.qty).toFixed(2);
}
function savingLine(amount) {
return 'Saved: $' + amount.toFixed(2);
}
function totalLine(amount) {
return 'Total: $' + amount.toFixed(2);
}
function printReceipt(cart, saving, total) {
for (const item of cart) console.log(itemLine(item));
console.log(savingLine(saving));
console.log(totalLine(total));
}
printReceipt(cart, 24.5, 220.5);
The output:
Plain Black Tee x2: $150.00
Coffee Print Tee x1: $95.00
Saved: $24.50
Total: $220.50
The way to write a price, '$' + amount.toFixed(2), is one piece of knowledge. In that code it's written three times: in itemLine, savingLine and totalLine.
Duplication doesn't cause errors
Duplication is the same knowledge copied into more than one place. Say Raka starts selling abroad and asks for the format USD 220.50. You change itemLine and totalLine, but forget savingLine:
Plain Black Tee x2: USD 150.00
Coffee Print Tee x1: USD 95.00
Saved: $24.50
Total: USD 220.50
No error, the program keeps running. Duplication only makes the result quietly inconsistent. The more copies there are, the more likely one gets missed.
One function, one place
Move the way to write a price into one function, and have every place call it:
function formatPrice(amount) {
return '$' + amount.toFixed(2);
}
function itemLine(item) {
return item.name + ' x' + item.qty + ': ' + formatPrice(item.price * item.qty);
}
function savingLine(amount) {
return 'Saved: ' + formatPrice(amount);
}
function totalLine(amount) {
return 'Total: ' + formatPrice(amount);
}
- The output is exactly the same as before. So this change is a refactor: the shape of the code changes, the result stays.
- Changing the format now takes one line, in
formatPrice, and all four receipt lines change with it. toFixedappears only once in the whole code. That's an easy way to check that the duplication is gone.- This
formatPriceis the same one that appeared in the Small, Focused Functions lesson.
The same goes for numbers. Say a tax rate of 0.11 is written on three lines: price * 0.11, shipping * 0.11, service * 0.11. Move that number into one constant, const TAX_RATE = 0.11;, and have all three lines use TAX_RATE. When the rate changes, one line changes. The constants VOUCHER_DISCOUNT, FREE_SHIPPING_MIN and SHIPPING_FEE in Raka's checkout are the same idea.
Looking alike isn't being the same
Raka also has resellers (people who buy his T-shirts to sell them again) with a 10% contract discount. The checkout code has two numbers that happen to be equal:
const VOUCHER_DISCOUNT = 0.1; // SAVE10 promo, set by marketing
const RESELLER_DISCOUNT = 0.1; // reseller contract, written in the agreement
The temptation: "they're both 0.1, merge them into DISCOUNT_RATE". Next month marketing raises the promo to 15% and changes DISCOUNT_RATE to 0.15. A reseller ordering $245 gets 15% too, and pays $208.25. But the contract says 10%, so the reseller should pay $220.50.
Two pieces of code that look the same, but change for different reasons, are called coincidental duplication. If you merge them, the result is the wrong abstraction. An abstraction here is one name, such as a function or a constant, that several places share. The wrong abstraction makes one change spread to a place it shouldn't reach. Sandi Metz wrote (2016): "duplication is far cheaper than the wrong abstraction".
The question that tests whether two pieces of code may be merged: if one rule changes, must the other change with it? The price format on three receipt lines: yes, so merge. A marketing promo and a reseller contract: no, so keep two. When you are not sure, many developers wait until the same pattern appears three times (the rule of three) before merging.
The exercise: formatPrice
In the exercise, showProduct, showCartTotal and showDiscount each format on their own. Write function formatPrice(amount) that returns '$' + amount.toFixed(2), then make all three functions call it. toFixed may be written only once in the whole code. The output stays:
Laptop: $900.00
Total: $400.00
$200.00 -> $150.00
formatPrice is also tested on its own with other numbers: formatPrice(12.5) must give '$12.50'.
⚠️ DRY taken too far, and DRY left half done
- Merging things that only look alike. The promo and the reseller contract are both 0.1 today, but they change for different reasons. One constant for both is a bug that will appear one day.
- Missing one copy. Duplication doesn't cause errors, so a missed copy is only noticed when someone reads the receipt.
- Formatting left outside the function. If
showCartTotalstill callstoFixeditself, the duplication isn't gone and the exercise's rule fails. - A formatter that's only right for one number.
return '$200.00'is right for one example, butformatPrice(12.5)must give'$12.50'. - DRY isn't about saving keystrokes. The goal is a single source of truth: one place that holds each rule. A longer but clearer name is still better.
TL;DR: DRY (Don't Repeat Yourself) means every piece of knowledge, that is every rule the program uses, has one place. When a price format is copied into three receipt functions, one copy will be missed one day, for example when $ changes to USD. The receipt then mixes USD and $, with no error. Move the format into formatPrice(amount), call it from every place, and make sure toFixed, the method that formats the number, appears only once. A repeated number, like a tax rate of 0.11, moves into a constant (TAX_RATE). But don't merge two pieces of code that happen to look alike and change for different reasons (a promo vs a reseller contract). Duplication is cheaper than the wrong abstraction: a shared function or constant that makes a change spread to the wrong place. Before merging, ask: if one changes, must the other change too?
⚡ One piece of knowledge, three copies
Write:
function savingLine(amount) {
return 'Saved: $' + amount.toFixed(2);
}
function totalLine(amount) {
return 'Total: $' + amount.toFixed(2);
}
Guess first: these two receipt functions, and one more for the item lines, each write the price on their own. Raka, the shop owner, asks for the USD format. You change two functions, but forget savingLine. What error do you get?
None. The program keeps running, but the receipt is mixed: Saved: $24.50 between lines that already say USD. Duplication makes the result quietly inconsistent.
Meaning: DRY (Don't Repeat Yourself) means every piece of knowledge in a program (a rule it uses, such as the way to write a price) has one place. Here that rule is written three times. The same knowledge copied into several places is called duplication.
⚡ One function, one place
Write:
function formatPrice(amount) {
return '$' + amount.toFixed(2);
}
function totalLine(amount) {
return 'Total: ' + formatPrice(amount);
}
Meaning: The way to write a price now lives in one function, formatPrice, so changing the format takes one line. toFixed appears only once in the whole code. That's an easy way to check that the duplication is gone. A repeated number, like a tax rate of 0.11, moves into a constant TAX_RATE.
⚡ Looking alike isn't being the same
Write:
const VOUCHER_DISCOUNT = 0.1; // SAVE10 promo, set by marketing
const RESELLER_DISCOUNT = 0.1; // reseller contract, written in the agreement
Guess first: these two constants get merged into DISCOUNT_RATE, then marketing raises the promo to 15%. What does a reseller (a buyer who sells again) ordering $245 pay?
$208.25, while the contract says 10%, so it should be $220.50. That's coincidental duplication: it looks the same, but changes for a different reason.
Meaning: Before merging, ask: if one rule changes, must the other change with it? If not, keep two. Duplication is far cheaper than the wrong abstraction: a shared constant or function that makes a change spread to a place it shouldn't reach.