2.2.1Design Principles

DRY — Don't Repeat Yourself

1,858 words8 min readdifficulty · medium2 backlinks

WHAT is DRY?

The subtle trap: DRY is about knowledge, not about text. Two lines of code that look identical but represent two unrelated decisions are not a DRY violation. (More on this in the mistakes section — this is the #1 misunderstanding.)


WHY does DRY matter?

Concretely, duplication hurts on three axes:

Axis What goes wrong with duplicates
Maintainability One change → many edits → forget one → bug
Consistency Copies "drift" apart over time
Readability Reader can't tell if two copies are meant to be identical
Figure — DRY — Don't Repeat Yourself

HOW do you apply DRY?

Worked Example 1 — Extract a function (logic duplication)

WET (bad):

# order A
total_a = price_a + price_a * 0.18
# order B
total_b = price_b + price_b * 0.18

Why bad? The rule "total = price + 18% tax" lives in two places. Change tax → 2 edits.

DRY (good):

TAX_RATE = 0.18                       # Why? the FACT lives once
 
def with_tax(price):                  # Why? the LOGIC lives once
    return price + price * TAX_RATE
 
total_a = with_tax(price_a)
total_b = with_tax(price_b)

Why this step? Now changing the tax = edit one constant. n=1n=1.

Worked Example 2 — Single source of truth (data duplication)

WET: A list of US states hard-coded in the frontend dropdown and in the backend validator. Why bad? Add a state → must edit both, or they drift and validation rejects valid input.

DRY: Define the list once (one config/DB table), and have both layers read it. Why this step? The "knowledge" (what states exist) has one authoritative source.

Worked Example 3 — Loop instead of copy-paste

WET:

draw_button("Save")
draw_button("Cancel")
draw_button("Help")

DRY:

for label in ["Save", "Cancel", "Help"]:   # Why? structure expressed once
    draw_button(label)

Why this step? The procedure of drawing a button is now described one time; the data varies.


When NOT to DRY (the steel-man)


Active Recall

Recall What does DRY actually forbid — duplicate text or duplicate knowledge?

Duplicate knowledge (a logic/rule/fact represented in more than one authoritative place). Identical text that encodes unrelated decisions is not a violation.

Recall Why does forgetting-probability matter in the DRY argument?

Because the chance that all nn copies stay consistent is (1p)n(1-p)^n, which decays exponentially. More copies → much higher chance of a missed edit → silent bug.

Recall What is the Rule of Three?

Wait until you see the third occurrence of duplication before abstracting, so the real pattern is clear and you avoid the wrong abstraction.

Recall Give the cheaper-than alternative quote about wrong abstractions.

"Duplication is far cheaper than the wrong abstraction." — Sandi Metz.


Feynman: explain to a 12-year-old

Recall Explain DRY simply

Imagine you wrote your home address on 5 different notebooks. If you move house, you'd have to find and fix all 5 — and if you miss one, someone gets lost. Instead, write your address in one notebook and tell everyone "look there". Now moving means changing it once. DRY in code means: keep each important fact or rule in one place, and have everything else point to it.



Connections

  • Single Responsibility Principle — "one reason to change" is the test for true duplication.
  • WET — Write Everything Twice — the anti-pattern DRY opposes.
  • Rule of Three — when to delay DRYing.
  • Single Source of Truth — DRY applied to data/config.
  • Premature Abstraction / The Wrong Abstraction — DRY taken too far.
  • KISS Principle & YAGNI — balance DRY against simplicity.
  • Refactoring — Extract Method — the practical tool for removing logic duplication.

DRY stands for?
Don't Repeat Yourself.
DRY's core rule (Pragmatic Programmer definition)?
Every piece of knowledge must have a single, unambiguous, authoritative representation in the system.
Does DRY target duplicate text or duplicate knowledge?
Duplicate knowledge (logic/rules/facts), not coincidentally-identical text.
Edit cost vs number of copies n?
Grows linearly: C = n·c.
Probability all n copies stay consistent if slip-prob is p?
(1−p)^n — decays exponentially.
What is accidental/coincidental duplication?
Code that looks the same but encodes unrelated decisions that change for different reasons; should NOT be merged.
Test to decide if duplication is real?
"Do they change together for the same reason?" Yes → DRY them; No → keep separate.
Rule of Three?
Tolerate duplication until the third occurrence, then extract the abstraction.
Sandi Metz on abstractions?
"Duplication is far cheaper than the wrong abstraction."
Opposite of DRY?
WET — Write Everything Twice.
DRY for data/config is called?
Single Source of Truth.
Main risk of over-DRYing?
Premature/wrong abstraction with too many flags, harder to read than the original duplication.

Concept Map

means

about

opposite of

causes

raises

lowers

hurts

hurts

applied by

references

via

DRY Principle

Single Authoritative Representation

Knowledge not Text

WET Duplication

Multiple Copies n

Edit Cost = n·c linear

Consistency 1-p to the n

Maintainability

Copies Drift Apart

Extract to Single Home

Function Constant Class Template

Hinglish (regional understanding)

Intuition Hinglish mein samjho

DRY ka matlab hai "Don't Repeat Yourself" — yaani koi bhi ek important baat (logic, rule, ya fact) tumhare poore code me sirf ek hi jagah honi chahiye. Socho tax rate 18% tumne 5 alag files me likh diya. Jis din rate badlega, tumhe paanchon jagah dhoondh-dhoond ke change karna padega, aur ek bhi miss hui to chupke se bug aa jayega. DRY bolta hai: us fact ko ek constant ya function me daalo, baaki sab usi ko point karein. Phir change sirf ek jagah hota hai.

Important baat: DRY text duplication ke baare me nahi, knowledge duplication ke baare me hai. Agar do lines bilkul same dikhti hain par unke change hone ki wajah alag-alag hai (jaise MAX_USERS = 100 aur RETRY_LIMIT = 100), to unhe merge mat karo — warna do unrelated decisions aapas me coupled ho jayenge aur baad me dard hoga. Test simple hai: "Kya ye dono ek hi wajah se, ek saath badalte hain?" Haan → merge karo (DRY). Nahi → alag rehne do.

Lekin DRY ko over-mat karo. Bahut jaldi ek "super flexible" function bana dena jisme 10 flags ho, woh duplication se bhi bura hota hai. Sandi Metz ne bola hai — "duplication is far cheaper than the wrong abstraction". Isliye Rule of Three follow karo: jab tak teesri baar same cheez na dikhe, abstraction mat banao. Math se bhi clear hai: n copies ke saath edit cost linearly badhti hai (n·c) aur sab consistent rehne ki probability exponentially girti hai ((1-p)^n). Isiliye "One Fact, One Home" yaad rakho.

Go deeper — visual, from zero

Test yourself — Design Principles

Connections