liveBook · Manning

Open-closed principle

As explained in Software Design for Python Programmers

The Open-Closed Principle states that a class should be closed to modification but open to extension.

The Open-Closed Principle keeps a class stable by closing it to modification while opening it to extension. A superclass captures common state and behavior; subclasses add specialized attributes and operations without changing that superclass. This combination provides stability and flexibility, while supporting loose coupling and encapsulation. section 2.3.3 section 5.8

Apply the principle by separating common behavior from specialized behavior:

  • Put shared state and methods in a superclass, such as Attributes or Mammal. section 2.3.3
  • Hide the superclass implementation behind private instance variables and public properties or methods. section 5.8
  • Reuse common operations through inheritance, such as calling super().is_match() and super().__str__(). section 2.3.3
  • Avoid treating subclass proliferation as automatic progress: too many classes and runtime type checks can signal a poor design. section 2.4

Book attributes and mammals

Attributes stores title, author names, matching, and rendering. FictionAttrs extends it with year and genre; CookbookAttrs extends it with region. Neither subclass changes the common implementation. Similarly, Mammal keeps weight, height, sleeping, and abstract operations stable, while Human adds reading behavior and Cat adds shedding behavior. Clients can use inherited operations while each subclass supplies its specialized implementation.

The principle also works with the Strategy Design Pattern. Sport remains closed to changes while interchangeable player and venue strategies extend its behavior; clients can even replace a venue strategy at run time. section 8.2.3

How Software Design for Python Programmers covers it

How deep it goes
Explains superclass design, private state, inherited calls, abstract methods, and runtime strategies, while warning against unnecessary subclass complexity.
Examples
Demonstrates book attributes, mammals, and sports whose specialized subclasses or strategies extend stable common implementations.
What it assumes
Assumes classes, inheritance, subclasses, private members, abstract methods, and polymorphic interfaces.
What you can do after
Build it from scratch by isolating common behavior, hiding implementation details, and adding specialized subclasses or interchangeable strategies.
How it connects
Connects inheritance, encapsulation, loose coupling, polymorphism, Code to the Interface, and the Strategy Design Pattern.

Also explained in

Compare how 3 books explain open-closed 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.