liveBook · Manning

Don't repeat yourself principle

As explained in 100 C++ Mistakes and How to Avoid Them

The DRY principle is the software design principle of avoiding repeated knowledge or behavior across multiple implementations.

The DRY principle reduces repeated knowledge or behavior by establishing a minimal basis of essential operations. Duplication is a warning sign, not an absolute rule: centralizing behavior prevents implementations from diverging and lowers cognitive load. section 7.5

Duplicated cylinder calculations

Several Cylinder constructors separately calculate area and volume. That repetition makes inconsistent behavior more likely: one implementation can change while the others remain unchanged. The same reasoning applies to methods and standalone functions. section 7.5

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains minimal function bases and demonstrates consolidation, while stopping short of treating every duplication as requiring refactoring.
Examples
Uses a Cylinder with repeated area and volume calculations, then centralizes initialization and derives volume from base area.
What it assumes
Assumes familiarity with constructors and functions while developing the idea of a minimal basis for shared behavior.
What you can do after
Apply it via identifying duplicated behavior and selecting a minimal set of shared operations from which other functions can be implemented.
How it connects
Connects DRY with constructors, methods, standalone functions, class invariants, and code divergence.

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 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.