DRY
easy 40 minDon't repeat yourself: every piece of knowledge has one home, and everything else asks that home.
Video lesson · Chapter 1 of 6
Make a prediction
DRY
1:06Reel
More reels
One idea each, a minute or less.
DRY, or leave it?
0:33Reel
Theory
Read or listen first. About 3 min.
What it is
DRY means don't repeat yourself. Andy Hunt and Dave Thomas wrote it as a rule about knowledge: each piece of it should have one clear, trusted place in the system.
Knowledge is anything that can become false. A tax rate, the rule for a valid email, the shape of a message, the steps of a release. If it changes, how many places must you edit? DRY wants the answer to be one.
DRY is not a ban on lines that look alike. Two functions may have the same text and still mean different things. And two pieces of code may look quite different and hold the same rule. The question is always: would they change together, for the same reason?
The opposite got the joke name WET: write everything twice, or we enjoy typing.
Why it exists
A copy does no harm on the day it is made. The harm comes with the first change. Somebody must remember every copy, find it, edit it in the same way and test it. One forgotten copy is a bug, and the program now gives two answers to one question.
One home makes the change small, the test small and the code shorter to read. It also gives the rule a name. People can talk about EmailAddress, and not about those six lines in three files.
But sharing has a price: everybody who shares a piece now depends on it. So DRY pays only for real shared knowledge. Shared accidents cost more than copies.
A short history
1970
Edgar Codd introduces database normalization. The aim is close to DRY for data: keep a fact once, so that it cannot contradict itself.
1999
Andy Hunt and Dave Thomas name the DRY principle in The Pragmatic Programmer.
1999
Martin Fowler's Refactoring makes the rule of three popular, and credits it to Don Roberts: when the same thing is written a third time, extract it.
2003
In an interview with Bill Venners, Hunt and Thomas explain that DRY is about knowledge and not only about code, and that a generator may make copies if one source stays in charge.
2016
Sandi Metz writes The Wrong Abstraction (20 January): duplication is far cheaper than the wrong abstraction.
2019
The 20th anniversary edition of The Pragmatic Programmer appears.
Words to know
- Knowledge
- A fact, rule or decision that can change.
- Single source of truth
- The one place that is right when places disagree.
- WET
- Write everything twice. A joke name for the opposite.
- Accidental duplication
- Code that looks the same today but belongs to different rules.
- Wrong abstraction
- Shared code that serves several needs with flags and branches, because the needs were never the same.
- Rule of three
- Copy once if you must. At the third time, extract.
- Extract function
- Move repeated steps into one named function and call it.
- Derived copy
- A copy that a machine makes from the source, such as generated code or a cache.
- Coupling
- How much one part must know about another. Sharing code adds coupling.
- Normalization
- Arranging tables so that each fact is stored once.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Spot. The same fact in two places
Understand it
Start here
Five doors, one fact
Noor looks after a village hall with five doors. People want to know when it is open. Noor takes a brush.
Frames 1 to 5 are DRY. Frames 6 and 7 are the part that people forget.
The smell
Three functions that check one thing
Registering, changing the address and asking for a new password all check an email. Somebody copied the check, because it worked.
def register(email): if email is None or email == "": raise ValueError("email required") if "@" not in email: raise ValueError("invalid email") return "registered " + emaildef update_email(email): if email is None or email == "": raise ValueError("email required") if "@" not in email: raise ValueError("invalid email") return "changed to " + emaildef send_reset(email): if not email or "@" not in email: # the same rule in other words raise ValueError("invalid email") return "mail to " + emailfor f in (register, update_email, send_reset): print(f("abc@")) # accepted everywhere: a bugabc@ is accepted in all three places. The bug must be found and fixed three times.Look at send_reset. It does not have the same text. A tool that compares lines will not find it. It still holds the same rule, so it must change with the other two. This is logic duplication, and it is harder to see than copied text.
The bad shape: every class owns the rule
1/3Registration
The first class checks an email in its own private method. With one user of the rule, this is fine.
The good shape: the rule has a home
1/4A home
EmailAddress can only be made by parse. If you hold one, it has been checked.
uses
def check_email(text): text = (text or "").strip() name, at, domain = text.rpartition("@") if not (at and name and "." in domain.strip(".")): raise ValueError("email: expected name@domain") return textdef register(email): return "registered " + check_email(email)def update_email(email): return "changed to " + check_email(email)def send_reset(email): return "mail to " + check_email(email)for f in (register, update_email, send_reset): try: print(f("abc@")) except ValueError as e: print("refused:", e)print(register("noor@hall.example"))abc@ was one line.DRY
- Extract the repeated steps into a function
- A named constant for a number with meaning
- One source of truth
- A bug is fixed in 1 place
WET
- The same code in several places
- Copied and pasted logic
- The same magic number again and again
- A bug is fixed in N places, if all are found
How it works
What one change costs
A fix with copies
A fix with one home
The same change, counted
| n copies | One home | |
|---|---|---|
| Edits by hand | n, if all are found | 1 |
| Test files that must know the rule | n | 1 |
| Chance to forget one | Grows with n | None |
| Places to read to understand the rule | n, and then you compare them | 1 |
| Who is touched by a mistake in the rule | One caller | All callers |
| Extra jump while reading a caller | None | One |
Where it hides
Seven kinds of duplication
Code
The same steps pasted into several functions or files. Fix: extract a function or a class, share by composition.
Logic
The same rule written in different words, often by people who did not know of each other. Fix: one home for the business rule.
Data
A member's email in the users table, in orders and in comments. Fix: store it once and refer to it by key.
Configuration
One service address typed into 15 files. Fix: one setting, read from the environment or a config file.
Magic numbers
0.08in four formulas. Fix: a named constant, or better a function that owns the formula.Documentation
A comment repeats what the code says, and stays when the code changes. Fix: clear names, and comments that tell why.
Process
Release steps on a wiki page and in three heads. Fix: a script that does them.
TAX_POINTS = 800 # 8.00 percent, in hundredths of a percentdef with_tax(cents): # the home: rate AND rounding return cents + (cents * TAX_POINTS + 5000) // 10000def order_total(prices): return with_tax(sum(prices))def subscription_total(monthly, n): return with_tax(monthly * n)def service_fee(hours, rate): return with_tax(hours * rate)print(order_total([1999, 501])) # 2700print(subscription_total(900, 12)) # 11664print(service_fee(3, 4550)) # 14742Tools
Ways to give a fact one home
| Technique | Use it when | Take care |
|---|---|---|
| Extract function | Steps repeat | Give it a name from the problem, not doStuff |
| Named constant | A value repeats and means one thing | SECONDS_PER_DAY and MAX_ITEMS may be equal and must stay two constants |
| Value class | A check travels with the value | Make unchecked values impossible |
| Composition | Several classes need a service | Hand it in from outside |
| Inheritance | Subclasses truly are the parent | Not only to reuse lines. See inheritance or composition |
| Generics, templates | Only the type differs | One print_list for numbers and words |
| Table of data | Branches differ only in values | Rows instead of code |
| Config, environment | A value differs per deployment | One loader, checked at start |
| Generated code | Two languages need one shape | Never edit the output by hand |
const BASE = "https://api.hall.example";async function apiGet<T>(path: string, token: string): Promise<T> { const res = await fetch(BASE + path, { headers: { Authorization: "Bearer " + token, Accept: "application/json" }, }); if (!res.ok) throw new Error(path + " failed with " + res.status); return (await res.json()) as T;}export const getUsers = (t: string) => apiGet<{ id: string }[]>("/users", t);export const getRooms = (t: string) => apiGet<{ id: string }[]>("/rooms", t);export const getOrders = (t: string) => apiGet<{ id: string }[]>("/orders", t);The hard part
Same text, different knowledge
def password_ok(text): return len(text) >= 8def voucher_ok(text): return len(text) >= 8# Merged by somebody who saw only the text:def long_enough(text): return len(text) >= 8# Safety now asks for 12. Change long_enough, and every printed voucher stops working.print(long_enough("SPRING26"))Should these two become one?
validateAndFormatAndSave, it is not one piece of knowledge.Two services both round prices. One is written in Python, the other in Java. What do you do?
BreaksIgnore it
- How
- Each team keeps its own function.
- Limit
- They will differ by a cent some day, and the customer sees both numbers.
- Choose when
- Only if no two results are ever compared.
WorksOne shared service
- How
- A pricing service answers, and both call it.
- Limit
- A network call, and an outage that stops both, for one line of arithmetic.
- Choose when
- When the rule is large and changes often.
StrongOne table of examples
- How
- A file of inputs and expected cents lives in one place. Both test suites must pass it. The rule is owned once, and written twice.
- Limit
- The examples must cover the edges: halves, zero, negatives, big values.
- Choose when
- Small stable rules in several languages.
The life of a wrong abstraction
From copies to one home in five safe moves
- 1
Pin
Write tests with real inputs against every copy. If two copies answer differently, you have found a question for the owner.
- 2
Name
Say the rule in one sentence. The noun of the sentence is the name.
- 3
Build
Write the home with its own tests. Nobody calls it yet.
- 4
Move
Switch one caller at a time, and run the tests after each.
- 5
Guard
Delete the copies, and make a new copy hard: a type, a lint rule, or a private constructor.
Neighbours
How it fits with other principles
| Principle | Its relation to DRY |
|---|---|
| KISS | A copy of two lines may be simpler than a shared helper with three parameters |
| YAGNI | Do not build a shared framework for a second user who does not exist |
| Single responsibility | Both ask for the reason to change. DRY gathers one reason into one place, SRP keeps other reasons out |
| Reducing coupling | Every shared piece is a tie. Share inside one owner freely, share between teams with care |
| Open/closed | The shared core is written once, the variants come from outside |
Summary
The whole topic in one minute.
DRY is about knowledge. Ask: if this fact changes, how many places do I edit by hand? One is the goal.
Same text is only a hint. Merge two pieces if one reason changes both. Keep them apart if they only look alike today.
When copies must exist (two languages, two services, a fast read), keep one source in charge, let a machine make the copies, and let a test fail when a copy is old.
- DRY is about knowledge, not about lines.
- Test: if this fact changes, how many places do I edit by hand?
- Equal text is a hint. One reason to change is the proof.
- Give the fact a name, a home and a test. Let everybody else refer to it.
- A little copying is cheaper than the wrong abstraction.
- If copies must exist, one source is in charge and a machine makes the rest.
Sources
- Andy Hunt and Dave Thomas with Bill Venners: Orthogonality and the DRY Principle (2003)
- The Pragmatic Programmer, 20th anniversary edition
- Sandi Metz: The Wrong Abstraction (2016)
- Wikipedia: Rule of three
- Wikipedia: Database normalization
- Ruby on Rails guides: Getting started
- Django: Design philosophies
- React: Choosing the state structure