Definition
Open-Closed Principle (OCP) states that software entities (classes, modules, functions) should be open for extension but closed for modification. This means you should be able to add new functionality without changing existing code.
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.
Interview Tip: Always mention both parts: "open for extension" means new behavior can be added, and "closed for modification" means existing source code should not change. Many candidates only mention one aspect.
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.
When to Apply: Use OCP when you anticipate variation in a specific dimension (payment methods, notification types, discount strategies). However, if requirements are truly stable and unlikely to change, applying OCP prematurely adds unnecessary complexity.
✓Open for extension: new behavior can be added without touching existing code
✓Closed for modification: existing source code remains unchanged
✓Reduces risk of breaking working functionality when requirements evolve
✓Achieved through abstraction, polymorphism, and dependency inversion
✓Apply when you expect variation; avoid premature abstraction if requirements are stable