liveBook · Manning

Don't repeat yourself principle

As explained in Python Workout: 50 ten-minute exercises

The software-development principle of avoiding duplicated knowledge or logic by defining it once and reusing it.

Repeated logic may run correctly, but it makes maintenance harder: every improvement or bug fix must be found and applied in several places. DRY means defining knowledge or behavior once, then reusing it. section 6.0 section 8.0

Prefer the compact condition

A repeated vowel comparison such as `if (word[0] == 'a' or word[0] == 'e' or word[0] == 'i' or word[0] == 'o' or word[0] == 'u'):` can become the clearer `if word[0] in 'aeiou':`. The shorter expression is readable, accurate, and uses Python's sequence membership operation. section 2.3

Choose the reuse boundary that matches where repetition occurs:

  • Use a function when identical instructions recur within one program. A named function packages behavior, supports repeated calls, and lets the rest of the program operate at a higher level of abstraction. section 6.0
  • Use a module when the same functions, classes, or data must be shared across programs. Importing the definition avoids reimplementing it and reduces the cognitive load of its implementation details. section 8.0 section 8.11
  • Use inheritance when related classes share behavior. A subclass reuses its parent’s functionality and adds more specific behavior, although initialization must be designed so shared attributes are set correctly. section 9.15

Python functions add flexibility because they are objects: code can store them in data structures and retrieve them as data. This can reduce code while preserving reusable, named operations. section 6.0

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains motivations and reuse boundaries through Python examples, but does not develop a formal theory of duplication.
Examples
Uses vowel detection, reusable functions, shared modules, pricing formulas, and parent-child classes.
What you can do after
Build reusable Python functions, modules, and class hierarchies while recognizing repetitive expressions that deserve refactoring.
How it connects
Connects functions, modules, packages, abstraction, standard libraries, and inheritance.

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 Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.