DRY
DRY — Don't Repeat Yourself
"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." — Andy Hunt & Dave Thomas, The Pragmatic Programmer
Core idea
DRY is not about repeating lines of code — it's about repeating knowledge (business rules, formulas, constants, decisions). When the same piece of knowledge lives in two places, sooner or later they drift apart, and that drift becomes a bug.
Why it matters
| The duplication problem | The consequence |
|---|---|
| Change a formula/constant in one place, forget another | Silent bug — the stale value keeps running in the shadows |
| Logic repeated in N places | A requirement change = N edits + N test updates |
| "I'll copy and tweak it a bit" | A year later nobody remembers what exactly makes the variants different |
Example 1: duplicated constant
❌ Bad
def price_with_tax_ua(price: float) -> float:
return price * 1.20 # VAT 20%
def invoice_total_ua(items: list) -> float:
return sum(item.price * 1.20 for item in items) # 20% again
def export_for_accounting(orders: list) -> str:
return "\n".join(f"{o.id};{o.price * 1.20:.2f}" for o in orders) # and a third time
Tomorrow the rate changes to 18% — you'll update 1 out of 3 places. The other two will quietly keep computing the wrong number.
✅ Good
VAT_RATE = 0.20
def with_vat(amount: float) -> float:
return amount * (1 + VAT_RATE)
# all functions now go through with_vat() or VAT_RATE
Example 2: duplicated logic
❌ Bad
def is_valid_email(email: str) -> bool:
return "@" in email and "." in email.split("@")[1]
def send_welcome(email: str) -> None:
if "@" in email and "." in email.split("@")[1]: # same check
...
def add_to_newsletter(email: str) -> None:
if "@" in email and "." in email.split("@")[1]: # again
...
✅ Good
def is_valid_email(email: str) -> bool:
return "@" in email and "." in email.split("@")[1]
def send_welcome(email: str) -> None:
if is_valid_email(email):
...
When the validation rule changes, you change one function.
Example 3: duplicated structure
❌ Bad
print(f"{'ID':<5} {'Name':<20} {'Price':>10}")
print(f"{'-'*5} {'-'*20} {'-'*10}")
for p in products:
print(f"{p.id:<5} {p.name:<20} {p.price:>10.2f}") # format defined twice
✅ Good
ROW_FORMAT = "{id:<5} {name:<20} {price:>10}"
print(ROW_FORMAT.format(id="ID", name="Name", price="Price"))
print(ROW_FORMAT.format(id="-"*5, name="-"*20, price="-"*10))
for p in products:
print(ROW_FORMAT.format(id=p.id, name=p.name, price=f"{p.price:.2f}"))
The main trap: accidental duplication
DRY ≠ "merge everything that looks alike." If two pieces of code happen to look similar by coincidence (mathematically or syntactically) rather than because they express the same knowledge — merging them makes things worse.
def area_rectangle(w: float, h: float) -> float:
return w * h
def salary(rate: float, hours: float) -> float:
return rate * hours
The formula is identical. The knowledge is not. When tomorrow's requirement adds overtime multipliers to salary, a function shared with area_rectangle will break under it.
Martin Fowler (Refactoring) puts it bluntly:
Duplicate first — until you can see the real pattern. Then generalize.
The rule of three: don't abstract until you've seen the third identical case. Two cases are still a coincidence.
When NOT to apply DRY
- Tests — duplication in tests is often fine; explicitness beats conciseness.
- Documentation and comments — repeating information in a comment is acceptable if it helps the reader.
- Accidental similarity — see above.
- Premature abstraction — two pieces that look alike today but might diverge tomorrow are better left separate.
Checklist: is this really a DRY violation?
- Is it the same piece of knowledge (rule, formula, decision)?
- If the requirement changes tomorrow, must it change identically in all places?
- Do you already have ≥ 3 identical cases?
Three yeses — extract it. A single no — leave it alone; the duplication may be temporary.
One-line summary
One piece of knowledge → one place in the code. But don't confuse knowledge with accidental similarity.