liveBook · Manning

Rule of three

As explained in Practices of the Python Pro

The rule of three is a refactoring heuristic that recommends introducing an abstraction after similar behavior has been implemented about three times.

The rule of three is a refactoring heuristic: after similar behavior has been implemented about three times, introduce an abstraction for it. Waiting until then balances duplicated code against premature generalization, because repeated use cases reveal what the abstraction should support. section 4.3.2

Use the heuristic as a practical refactoring guide:

  • Allow the first implementation to remain concrete. section 4.3.2
  • Observe the use cases that emerge when similar behavior is repeated. section 4.3.2
  • Refactor around the third implementation to provide a better-fitting abstraction. section 4.3.2

How Practices of the Python Pro covers it

How deep it goes
Defines the heuristic and its rationale but stops short of a detailed refactoring procedure.
Examples
Uses successive Python implementations that move from manual counting to defaultdict and Counter as refactoring illustrations.
What it assumes
Assumes familiarity with implementing behavior and introduces refactoring and abstraction as practical design choices.
What you can do after
Apply it by delaying abstraction until repeated implementations reveal a necessary and generalizable design.
How it connects
Connects refactoring with abstraction, duplicated code, use cases, and premature generalization.

Related concepts

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