🧩 OOP Concepts Intermediate

What is the Open/Closed Principle?

Answer

The Open/Closed Principle (OCP) states that software entities (classes, modules, functions) should be OPEN for extension but CLOSED for modification. You should be able to add new behavior without changing existing, tested code. Violation: class AreaCalculator { public double calculateArea(Object shape) { if (shape instanceof Circle circle) { return Math.PI * circle.radius * circle.radius; } else if (shape instanceof Rectangle rectangle) { return rectangle.width * rectangle.height; } // Adding Triangle requires modifying this method! else if (shape instanceof Triangle triangle) { return 0.5 * triangle.base * triangle.height; } return 0; } }. OCP applied — open for extension via abstraction: // Abstraction (closed for modification): interface Shape { double calculateArea(); } // Concrete implementations (extensions don't change existing code): class Circle implements Shape { private double radius; @Override public double calculateArea() { return Math.PI * radius * radius; } } class Rectangle implements Shape { private double width, height; @Override public double calculateArea() { return width * height; } } // Adding new shape -- NO modification to AreaCalculator: class Triangle implements Shape { private double base, height; @Override public double calculateArea() { return 0.5 * base * height; } } class AreaCalculator { public double calculateArea(Shape shape) { return shape.calculateArea(); // Closed -- never changes } public double totalArea(List<Shape> shapes) { return shapes.stream().mapToDouble(Shape::calculateArea).sum(); } } // Add Pentagon, Hexagon etc. without touching AreaCalculator!. OCP in practice: use interfaces/abstract classes for points of variation; use composition over conditional logic; plug-in architecture; Strategy pattern; Decorator pattern. OCP doesn't mean never modifying code — first write the code, then protect it from likely future changes.