AlgoViz

DRY

easy 40 min

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

0:00 / 4:18

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

developerPersonjobrefuse abc@registrationRegistrationcheckv1profileProfilecheckv1resetPasswordResetcheckv1

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 seeGive it a home
codesame function in 3 filesextract 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

    critical

    A password rule and a voucher format share a body today and nothing else.

    Wrong
    def long_enough(text): return len(text) >= 8
    Right
    def password_ok(text): return len(text) >= 8def voucher_ok(text): return len(text) == 8
  • A flag for each caller

    major

    Paths double, and a fix for one caller breaks another.

    Wrong
    render(doc, is_receipt=True)
    Right
    receipt(doc)
  • Constant shared, formula copied

    major

    Rounding is knowledge as well. Three totals round in three ways.

    Wrong
    total = cents * (1 + TAX_RATE)
    Right
    total = TAX.with_tax(cents, day)
  • Editing the generated file

    major

    The next run deletes the edit, or nobody dares to run it again.

    Wrong
    # member.sql, edited by hand
    Right
    MEMBER = (Field("name", "text", 1, 60),)   # then generate
  • The test uses the rule it tests

    minor

    If the rule is wrong, the expectation is wrong in the same way.

    Wrong
    assert total == with_tax(10000, day)
    Right
    assert 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