liveBook · Manning

Open-closed principle

As explained in AI-Powered Developer: Build software with ChatGPT and Copilot

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

The open-closed principle (OCP) says that software entities—classes, modules, and functions—should be open for extension but closed for modification. It is one of the SOLID principles used to make designs more flexible and maintainable. section 3.3 section 3.4

A practical approach is to introduce an abstraction that holds shared behavior, then add specialized implementations rather than repeatedly changing existing code. This keeps new needs localized while preserving the established model. section 3.3

Extending an asset model

An Asset parent class captures attributes shared by company assets. Hardware inherits from Asset, while future Software or Pitchfork subclasses can be added and treated as assets without altering the existing Hardware model. A DepreciationStrategy interface similarly supports swapping calculation approaches through concrete strategy implementations. section 3.3 section 3.3

Figure 3.5 We have added a depreciation strategy to our object model. This introduction allows us to swap out the method by which we can calculate the depreciation of an asset.

The class diagram makes the strategy interface and its concrete depreciation implementations visible, showing how a calculation method can be exchanged. section 3.3

How AI-Powered Developer: Build software with ChatGPT and Copilot covers it

How deep it goes
Defines OCP briefly and illustrates it through inheritance and strategy-interface changes, without developing a fuller implementation procedure.
Examples
Uses an Asset–Hardware hierarchy, possible Software and Pitchfork subclasses, and multiple depreciation strategies.
What it assumes
Introduces OCP with a brief definition while working from class diagrams, inheritance, interfaces, and concrete implementations.
What you can do after
Evaluate/understand whether a class model can accept new asset types or calculation strategies without modifying established entities.
How it connects
Connects OCP to SOLID, inheritance, interfaces, the Strategy pattern, and flexible maintainable design.

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 AI-Powered Developer: Build software with ChatGPT and Copilot. The section links point to the parts of the book it draws on.