liveBook · Manning

Don't repeat yourself principle

As explained in Software Design for Python Programmers

The Don't Repeat Yourself Principle states that each piece of knowledge or behavior should have a single authoritative representation in code.

The Don't Repeat Yourself (DRY) Principle says that each piece of knowledge or behavior should have one authoritative representation in code. Duplicate code enlarges programs, complicates maintenance, and creates change leaks when one copy is missed or changed differently. section 2.3.3

Recognize DRY violations through concrete design symptoms:

  • Repeated methods with nearly identical code multiply the changes required by new requirements. section 2.3.3
  • Growing subclass families and runtime isinstance checks signal that behavior has been scattered across type-specific code. section 2.3.3
  • Share repeated behavior through one separate function or one cohesive class, then use suitable design relationships rather than unnecessary subclasses. section 2.3.3 section 2.4

Toy behaviors before refactoring

ToyCar and TrainSet duplicate the same play implementation, while ToyCar and ModelAirplane duplicate the same sound implementation. Each subclass also hardcodes its play action and sound, so adding subclasses or changing behavior increases duplicated maintenance work. section 7.3.1

How Software Design for Python Programmers covers it

How deep it goes
Explains duplication, change leaks, and consolidation into functions or cohesive classes, but does not prescribe one universal refactoring.
Examples
Uses a polymorphic book catalogue and toy subclasses whose search, play, and sound implementations repeat code.
What you can do after
Apply it by locating repeated behavior and consolidating it into a single function or cohesive class.
How it connects
Connects duplication with subclasses, runtime type checks, polymorphism, the Delegation Principle, and the Open-Closed Principle.

Also explained in

Compare how 10 books explain don't repeat yourself principle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.