Don't Repeat Yourself (DRY)

Every piece of knowledge in a system has one authoritative home. DRY is about facts and rules, not about lines of code that happen to look alike.

Overview

DRY stands for Don't Repeat Yourself. Andy Hunt and Dave Thomas named it in The Pragmatic Programmer (1999): every piece of knowledge in a system should have a single, unambiguous, authoritative representation. Thomas has said the principle is widely misread as 'do not duplicate code'. It is about knowledge: a business rule, a limit, a format, a schema, a mapping. If that knowledge lives in two places, one day the two will disagree, and the bug will be found by a customer.

The mirror image matters just as much. Two pieces of code can look identical and still encode different knowledge, and merging them creates a coupling that hurts more than the duplication did. A strong interview answer shows both halves: you remove duplicated knowledge without hesitation, and you leave look-alike code alone until it proves it is the same thing.

One home for each fact

Duplication of knowledge shows up in more places than copied functions. Here is where the same knowledge hides, and the DRY fix for each.

  • Code: the same discount rule sits in two services. The fix is one function or module both call.
  • Constants: a limit is typed as a number in five files. The fix is one named constant.
  • Validation: the same email check runs in the form and in the API. The fix is one shared rule, with the API as the authority.
  • Schema: a stored total could be computed from the rows. The fix is to compute it, or to store it in one place with a clear owner.
  • Configuration: timeouts are copied into every service's config. The fix is one config source the services read.
  • Documentation: a comment restates the code. The fix is to let the code say it and document the why.

Here is what a repeated fact costs. Say the rule changes to 'free shipping over 50', and the limit lives in three files: checkout.py, cart_summary.py and invoice.py. The developer updates checkout.py and cart_summary.py but misses invoice.py, so invoices still use the old limit. With one home, the change is one edit. With three homes, the change must find all three, and the one it misses becomes a bug.

Interview questions

  • What is DRY really about, and what does a violation look like?
  • When does applying DRY make a codebase worse?
  • How do you apply DRY across a whole stack?
  • How does DRY relate to the single responsibility principle?
  • Does DRY apply to data and schemas?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio