What does the Open/Closed Principle mean?
The Open/Closed Principle (OCP) means that a module should be open for extension but closed for modification.
In detail:
1. The meaning of "open for extension"
A class's behavior should be able to change or expand, but not through changing its internal code - rather through adding new components: new classes, strategies, handlers, adapters. In other words, functionality should be extended from the outside.
2. The meaning of "closed for modification"
Code that is already written and tested should not change when new requirements appear. Any modification of existing logic creates a risk of introducing bugs, so OCP requires the base code to remain stable.
3. The rationale for the principle
When requirements change (and they always do), the architecture should allow adaptation without rewriting the old logic. This reduces the risk of regressions, increases the predictability of behavior, and speeds up development.
4. What counts as an OCP violation
- When adding a new behavior variant requires changing the body of an existing method.
- When new requirements force an already working class to be rewritten.
- When the core code has to be adapted to new conditions instead of plugging in new implementations.
5. What satisfies OCP
- Using interfaces and abstractions that allow new implementations to be substituted in.
- Applying patterns such as Strategy, Decorator, Factory Method, and polymorphism.
- An architecture where adding new behavior does not touch existing code.
Summary: OCP is a principle that makes code resilient to changing requirements: old code stays unchanged, and new behavior is added through extension, not modification.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.