The Open-Closed Principle says that a class should be closed for modification but open for extension. Stabilize code that captures common state and behavior, then add new functionality through subclasses rather than repeatedly changing the stable class. section 2.3.3 section 5.8
A book catalogue applies the principle with an Attributes superclass containing shared title, author, and matching behavior. FictionAttrs and CookbookAttrs extend it with year, genre, or region while Attributes remains unchanged; Book likewise stores an Attributes pointer instead of depending on one specific attribute type. section 2.3.3
Apply the principle by separating stable common behavior from variable extensions:
- Identify the common state and operations that the superclass can reliably stabilize. section 5.8
- Hide common implementation details with private members and expose only the needed interface. section 5.8 section 5.0
- Check the design for excessive subclasses, runtime type checks, and type conversions; these can signal that inheritance was a poor choice. section 2.4
Mammals with hidden implementation
Mammal keeps weight and height private, exposes common operations, and provides protected sleep behavior. Human and Cat extend it with their own state and implementations of eat() and perform(). The superclass can remain stable while new mammal types add behavior.


