AlgoViz

DRY

easy 40 min

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

CopyWhyWhat keeps it honest
Cache of a member's nameFast readsThe database is in charge, entry expires
Price on an order lineIt is another fact: the price on that dayNever updated
Number of members in a counterCounting is slowChanged in the same transaction, recounted at night
Expected values in a testThe test must not trust the codeWritten by hand on purpose
Check in the browser and on the serverQuick help for people, safety for usThe server is in charge
Python
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, right
Too DRY: the order points to the product, so an old bill changes when the price does. The copy of the price is the true record.
Edit and run it in your browser

Tests

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

    09:00

    Table has 100 members, counter says 100.

  2. 2

    09:01

    A row is inserted. The process dies before the counter is raised. Table 101, counter 100.

  3. 3

    Repair

    Put both in one transaction, so that both happen or none.

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