Explain the Open/Closed Principle with an example.

Beginner

Answer

The Open/Closed Principle states that software entities should be open for extension but closed for modification. You should be able to add new functionality without changing existing code.

Example:

// Violates OCP - need to modify for new shapes
class AreaCalculator {
    public double calculateArea(Object shape) {
        if (shape instanceof Rectangle) {
            Rectangle r = (Rectangle) shape;
            return r.width * r.height;
        } else if (shape instanceof Circle) {
            Circle c = (Circle) shape;
            return Math.PI * c.radius * c.radius;
        }
        return 0;
    }
}

// Follows OCP - extensible without modification
interface Shape {
    double calculateArea();
}

class Rectangle implements Shape {
    public double calculateArea() {
        return width * height;
    }
}

class AreaCalculator {
    public double calculateArea(Shape shape) {
        return shape.calculateArea();
    }
}