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
See it run
Objects at run time: where a fact lives, who asks for it, and what a change has to touch.
Operations
A fix with three copies
The check for an email has three owners. Follow one bug fix.
Step 1 of 6
Three owners
Each class has its own check. All accept abc@.
Step 1: Three owners
def register(email): if "@" not in email: raise ValueErrordef update_email(email): if "@" not in email: raise ValueErrordef send_reset(email): if not email.count("@"): raise ValueError- Good for
- Nothing, after the first day
- Costs
- One edit per copy
- Edits for one fix
- 3, if all are found
Search for the idea, not only for the text. The third copy uses `count`.
In the real world
The same dry doing real jobs. Pick one and step through it.
Duplication is more than pasted code.
Step 1 of 7
Code
| You see | Give it a home | |
|---|---|---|
| code | same function in 3 files | extract function |
| logic | ||
| data | ||
| config | ||
| numbers | ||
| docs | ||
| process |
Pasted steps. The easiest to see.
Step 1: Code
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Merged because they look alike
criticalA password rule and a voucher format share a body today and nothing else.
Wrongdef long_enough(text): return len(text) >= 8Rightdef password_ok(text): return len(text) >= 8def voucher_ok(text): return len(text) == 8A flag for each caller
majorPaths double, and a fix for one caller breaks another.
Wrongrender(doc, is_receipt=True)Rightreceipt(doc)Constant shared, formula copied
majorRounding is knowledge as well. Three totals round in three ways.
Wrongtotal = cents * (1 + TAX_RATE)Righttotal = TAX.with_tax(cents, day)Editing the generated file
majorThe next run deletes the edit, or nobody dares to run it again.
Wrong# member.sql, edited by handRightMEMBER = (Field("name", "text", 1, 60),) # then generateThe test uses the rule it tests
minorIf the rule is wrong, the expectation is wrong in the same way.
Wrongassert total == with_tax(10000, day)Rightassert total == 10850
Interview tips
Ask one question
- If this fact changes, what do I edit?
- Who asks for the change?
- Should the other follow?
Lightest tool first
- Constant, function, type, module
- Name it from the problem
- Test it once, fully
Leave apart on purpose
- Say why two similar parts stay
- Wait for the third
- Share between teams with care
When copies must exist
- One source is in charge
- A machine writes the copy
- A check finds an old one