Open/Closed Principle
Add new behavior by adding new code, not by editing code that already works. Abstractions make that possible; choosing which changes to close against makes it practical.
Overview
The Open/Closed Principle (OCP) says that software entities (classes, modules, functions) should be open for extension but closed for modification. Bertrand Meyer coined the phrase in Object-Oriented Software Construction in 1988. Robert C. Martin made it the first of his design principles in a 1996 C++ Report column, and it became the O in SOLID.
The two halves sound like a contradiction. Open for extension means the module's behavior can grow. Closed for modification means its source does not change. Martin's answer is abstraction: a module that depends on an abstract type is closed, because that type is fixed, yet its behavior can be extended by writing a new subtype.
Each half also has its own technique. New behavior is added by writing a new class that implements the abstraction. Working code stays unedited because the module calls the abstraction, never a concrete type.
Abstraction is the key
Martin's example is a drawing program. The procedural version keeps a type code on each shape and a function that switches on it. Every new shape means editing that function, and every edit risks the shapes that already work.
The object-oriented version gives each shape its own class behind one abstraction, as the diagram shows.
Interview questions
- How do you achieve the Open/Closed Principle in practice?
- What is the relationship between OCP and switch or if-else chains on a type?
- When is it fine to modify existing code?
- What does OCP cost, and when does it go too far?
- Refactor a shape-area calculator to follow OCP.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio