liveBook · Manning

Don't repeat yourself principle

As explained in Python Workout, Second Edition

The DRY principle is a software-development principle that avoids duplicating knowledge or logic by expressing it once and reusing it.

DRY means expressing knowledge or logic once instead of duplicating it. Repeated code is difficult to track and maintain because every copy must be found and updated when requirements change. Python functions apply DRY by packaging repeated behavior under a name, reducing duplication while enabling higher-level reasoning. section 7.0

Prefer a concise Python operation when repetition signals a better abstraction. To test whether a word begins with a vowel, replace a loop or chain of comparisons with `word[0] in 'aeiou'`; the expression is readable, short, accurate, and suitable for short strings. section 3.3

starts_with_vowel = False
for vowel in 'aeiou':
    if word[0] == vowel:
        starts_with_vowel = True
        break

Compare the repetitive vowel-checking loop with the shorter membership test represented by `b3`; the contrast illustrates DRY as a practical code-review heuristic. section 3.3

How Python Workout, Second Edition covers it

How deep it goes
Explains the maintenance rationale and demonstrates one Python refactoring, without developing broader design trade-offs.
Examples
Uses login, configuration, and MP3-length tasks plus a vowel-checking expression and alternative implementations.
What you can do after
Apply DRY via Python functions and membership testing when repeated logic or unusually long conditions appear.
How it connects
Connects DRY with functions, abstraction, sequences, membership testing, and Pythonic code.

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, Second Edition. The section links point to the parts of the book it draws on.