Open-Closed Principle: Definition and Core Problem
What Problem Does It Solve?
When requirements change, modifying existing classes introduces risk. Every change can break working code, requires retesting, and creates maintenance overhead. OCP minimizes this by allowing new behavior through extension mechanisms rather than modification.
Real-World Analogy
Consider a smartphone. You can add new capabilities by installing apps (extension) without modifying the phone's operating system code (closed for modification). The OS provides extension points (APIs) that apps use to add functionality.
Key Mechanisms for Achieving OCP
First, Abstraction: Define interfaces or abstract classes that represent stable contracts. Second, Polymorphism: Different concrete implementations can be swapped without changing client code. Third, Dependency Inversion: Depend on abstractions, not concrete classes.