liveBook · Manning

Open-closed principle

As explained in Object-Oriented Software Design in C++

A design principle stating that software entities should be closed for modification but open for extension.

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.

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains stability, encapsulation, subclass extension, and warning signs but stops short of prescribing inheritance for every design.
Examples
Demonstrates book attributes, Shape subclasses, and Mammal subclasses including Human and Cat.
What it assumes
Assumes basic classes and subclasses while teaching private members, protected members, virtual functions, and implementation hiding through examples.
What you can do after
Evaluate designs for stable common abstractions, useful extensions, hidden implementation, and harmful subclass or type-checking growth.
How it connects
Connects inheritance with encapsulation, loose coupling, polymorphism, and the Code to the Interface Principle.

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 Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.