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


