DRY
easy 40 minDon't repeat yourself: every piece of knowledge has one home, and everything else asks that home.
Watch lesson4:18
Copies on purpose
Caches, snapshots and tests: when repeating is right.
The point: a copy is allowed if you can say who is in charge, how it is refreshed and how old it may be. Or if it is a different fact.
Three good copies
Not every copy is a mistake
| Copy | Why | What keeps it honest |
|---|---|---|
| Cache of a member's name | Fast reads | The database is in charge, entry expires |
| Price on an order line | It is another fact: the price on that day | Never updated |
| Number of members in a counter | Counting is slow | Changed in the same transaction, recounted at night |
| Expected values in a test | The test must not trust the code | Written by hand on purpose |
| Check in the browser and on the server | Quick help for people, safety for us | The server is in charge |
product = {"name": "Hall, 1 hour", "cents": 2000}linked = {"product": product, "hours": 3} # no copyfrozen = {"product": product, "hours": 3, "cents": product["cents"]} # price on that dayproduct["cents"] = 2500 # price goes up laterprint("linked bill:", linked["product"]["cents"] * linked["hours"]) # 7500, wrongprint("frozen bill:", frozen["cents"] * frozen["hours"]) # 6000, rightTests
Let tests repeat a little
A test that uses the same helper as the code will repeat its mistake. Write the expected number: assert total == 10850, and not assert total == with_tax(10000). Share the boring set-up, and keep what matters for this test visible in it. A test should be read without jumping through five helpers.
Failure walk
A counter that drifts
- 1
09:00
Table has 100 members, counter says 100.
- 2
09:01
A row is inserted. The process dies before the counter is raised. Table 101, counter 100.
- 3
Repair
Put both in one transaction, so that both happen or none.
- 4
Safety net
A job compares each night, writes the difference to a metric, and repairs from the table, because the table is in charge.