What is the Open/Closed Principle? Is it always good, and how does it relate to Dependency Inversion?
Short answer
OCP: a module is open for extension, closed for modification; add behavior by adding a new class instead of editing code that already works. The way to get there is to depend on an abstraction and plug in new implementations, usually through Strategy.
3 points to say:
- OCP: add behavior with new code, don't edit code that already works.
- Achieved with DIP + Strategy, not inheritance.
- "Close" only at variation points you have actually seen; two cases is a
switch, refactor at the third case.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.