How does OCP work with inheritance vs composition?
Answer
OCP can be implemented through both inheritance and composition, but they have different trade-offs. Inheritance-based OCP: a base class provides default behavior, subclasses override to extend — the classic Template Method pattern. The risk is fragile base class problem — changes to the base class can unintentionally break subclasses. Composition-based OCP (preferred): a class delegates behavior to an interface, and new behavior is added by creating new implementations. This follows the Gang of Four advice: "prefer composition over inheritance." Composition-based OCP is more flexible because implementations can be mixed and matched at runtime, while inheritance is fixed at compile time. The Strategy, Decorator, and Chain of Responsibility patterns all use composition to achieve OCP.
Previous
What are the trade-offs of strictly following SOLID?
Next
What is the Barbara Liskov quotation that defines LSP?
More SOLID Principles Questions
View all →- Intermediate How would you refactor a class that violates SRP?
- Intermediate How does the Strategy pattern support OCP?
- Intermediate What are the conditions for LSP compliance?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?