AlgoViz

DRY

easy 40 min

Don'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

0:00 / 4:18

DRY

1:06Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1970

    Edgar Codd introduces database normalization. The aim is close to DRY for data: keep a fact once, so that it cannot contradict itself.

  2. 1999

    Andy Hunt and Dave Thomas name the DRY principle in The Pragmatic Programmer.

  3. 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.

  4. 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.

  5. 2016

    Sandi Metz writes The Wrong Abstraction (20 January): duplication is far cheaper than the wrong abstraction.

  6. 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.

Step 1 of 4

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.

Noor and the painted hours
VILLAGE HALL19 - 529 - 539 - 549 - 559 - 5

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.

Python
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 bug
Run it. abc@ is accepted in all three places. The bug must be found and fixed three times.
Edit and run it in your browser

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

Registration+ register(email)- checkEmail(text)

1/3Registration

The first class checks an email in its own private method. With one user of the rule, this is fine.

There are no arrows here, and that is the problem. Copies have no link to each other.

The good shape: the rule has a home

EmailAddress- value: String+ parse(text): EmailAddress+ equals(other): bool

1/4A home

EmailAddress can only be made by parse. If you hold one, it has been checked.

uses

Now the arrows exist. Anybody can ask the editor: who uses this rule?
Python
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"))
After. One check, three callers. The fix for abc@ was one line.
Edit and run it in your browser

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 callers were not edited. They asked the same question as before and got a better answer.

The same change, counted

n copiesOne home
Edits by handn, if all are found1
Test files that must know the rulen1
Chance to forget oneGrows with nNone
Places to read to understand the rulen, and then you compare them1
Who is touched by a mistake in the ruleOne callerAll callers
Extra jump while reading a callerNoneOne
The last two rows are the price. A shared rule needs a good test, because it can break everybody at once.

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.08 in 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.

Python
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))            # 14742
Numbers with meaning. Three totals share a rate and also the way to round. A constant alone would share only the rate.
Edit and run it in your browser

Tools

Ways to give a fact one home

TechniqueUse it whenTake care
Extract functionSteps repeatGive it a name from the problem, not doStuff
Named constantA value repeats and means one thingSECONDS_PER_DAY and MAX_ITEMS may be equal and must stay two constants
Value classA check travels with the valueMake unchecked values impossible
CompositionSeveral classes need a serviceHand it in from outside
InheritanceSubclasses truly are the parentNot only to reuse lines. See inheritance or composition
Generics, templatesOnly the type differsOne print_list for numbers and words
Table of dataBranches differ only in valuesRows instead of code
Config, environmentA value differs per deploymentOne loader, checked at start
Generated codeTwo languages need one shapeNever edit the output by hand
TypeScript
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 same request three times: address, headers, status check. One small client owns all of it. Each call says only what is special.

The hard part

Same text, different knowledge

Python
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"))
Two checks with the same body. A password needs at least 8 characters for safety. A voucher code has 8 because of the printer.
Edit and run it in your browser

Should these two become one?

If the best name is 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

Going back is not a defeat. It is the quickest way to see the true shape.

From copies to one home in five safe moves

  1. 1

    Pin

    Write tests with real inputs against every copy. If two copies answer differently, you have found a question for the owner.

  2. 2

    Name

    Say the rule in one sentence. The noun of the sentence is the name.

  3. 3

    Build

    Write the home with its own tests. Nobody calls it yet.

  4. 4

    Move

    Switch one caller at a time, and run the tests after each.

  5. 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

PrincipleIts relation to DRY
KISSA copy of two lines may be simpler than a shared helper with three parameters
YAGNIDo not build a shared framework for a second user who does not exist
Single responsibilityBoth ask for the reason to change. DRY gathers one reason into one place, SRP keeps other reasons out
Reducing couplingEvery shared piece is a tie. Share inside one owner freely, share between teams with care
Open/closedThe 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