Open/Closed Principle (OCP)
“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” This means you can add new functionality without changing existing code.Purpose
- Adapts to new requirements with minimal risk: new features can be added by extending existing code (e.g. via inheritance or composition) rather than altering working code.
- Prevents regressions, since existing classes remain untouched when extending behavior.
- Encourages flexible designs using polymorphism, interfaces, or abstract classes, so that core logic remains stable over time.
Minimal Example
The first function below violatesOCP: adding a new shape (e.g., Triangle) would require modifying the function to handle
it. The improved design uses polymorphism – an abstract Shape base class with a defined area() method. New shapes can be
extended by creating a subclass and overriding area(), with no changes needed to existing code.
More Realistic Example
Imagine a notification system that sends alerts via multiple channels (email, SMS, etc.). UsingOCP, we define a base
NotificationSender class and extend it for each channel. The client code can treat all senders uniformly through the base
interface. Adding a new channel (say, a push notification) is as simple as creating a new subclass, with no modifications
to the existing sending logic.