Open/Closed
The Problem
❌ Bad Example (Violates OCP)
public class AreaCalculator {
public double calculateArea(Object shape) {
if (shape instanceof Rectangle) {
Rectangle r = (Rectangle) shape;
return r.length * r.width;
} else if (shape instanceof Circle) {
Circle c = (Circle) shape;
return Math.PI * c.radius * c.radius;
}
return 0;
}
}
// Usage
Rectangle r = new Rectangle(5, 10);
Circle c = new Circle(7);
// To add Triangle, we must MODIFY AreaCalculator!✅ Good Example (Follows OCP)
Real-World Example: Notification Service
❌ Bad
✅ Good
How to Apply OCP
Interview Tips
Last updated