DRY Principle

Don’t Repeat Yourself — every piece of knowledge must have a single, unambiguous, authoritative representation within a system. Coined by Andrew Hunt and David Thomas in The Pragmatic Programmer, DRY is fundamentally about knowledge, not code. When the same knowledge is expressed in multiple places, a change to that knowledge requires finding and updating all copies — miss one and you have inconsistency. The principle extends beyond code to configuration, documentation, test fixtures, database schemas, and any artifact that encodes system behavior.

The failure mode DRY prevents is called WET code — “Write Everything Twice” or “We Enjoy Typing.” WET systems turn routine maintenance into archaeology, requiring developers to locate and synchronize every expression of the same fact rather than changing it in one place.

Key Concepts

  • Knowledge, not code: Two functions with similar implementations but different domain meanings are not a DRY violation. The question is whether they encode the same piece of knowledge, not whether they look alike.
  • The Rule of Three: Write something once, note it the second time, abstract it the third time. Premature abstraction based on two instances often produces the wrong generalization.
  • Impatient duplication: Copying is faster in the moment but creates compounding debt. Every duplicated piece of knowledge is a future bug waiting for a partial update.
  • Non-code duplication: Comments that restate what code does, documentation that mirrors API signatures, and test data that duplicates production schema are DRY violations even without duplicated code.
  • Wrong abstractions: Forcing unrelated code into a shared function to eliminate apparent duplication creates coupling between things that should be independent. Sometimes the right answer is to leave similar code separate.

Relationship to Other Principles

DRY supports Single Responsibility — when knowledge lives in one place, that place has one reason to change. It relates closely to the full DRY treatment, which covers types of duplication in depth. DRY and YAGNI interact: extracting a shared abstraction “in anticipation” of future duplication is speculative and violates YAGNI; apply DRY only when duplication actually exists.

Common Mistakes

  • Confusing coincidental similarity with knowledge duplication and creating false abstractions
  • Applying DRY to the wrong granularity — extracting at the function level when the duplication is at the module level
  • Ignoring non-code duplication (documentation, schemas, configuration)

References

  • Hunt, A., & Thomas, D. (1999). The Pragmatic Programmer. Chapter 2: The Evils of Duplication.
  • Martin, R. C. (2008). Clean Code: A Handbook of Agile Software Craftsmanship.