Software entities should be open for extension but closed for modification.

Example: Let’s say you have a class that calculates the area of different shapes.

// Violation of OCP
public class AreaCalculator {
    public double calculateArea(Object shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            return Math.PI * circle.getRadius() * circle.getRadius();
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            return rectangle.getWidth() * rectangle.getHeight();
        }
        return 0;
    }
}

// Following OCP
public interface Shape {
    double calculateArea();
}

public class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

public class Rectangle implements Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double calculateArea() {
        return width * height;
    }
}

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

Now, the AreaCalculator class doesn’t need to be modified when a new shape is introduced; you just create a new class implementing the Shape interface.

Previous: Single Responsibility Principle (SRP)

Next: Liskov Substitution Principle (LSP)

SOLID


2 responses to “Open/Closed Principle (OCP)”

  1. Marlon Avatar
    Marlon

    Your writing has a way of resonating with me on a deep level. It’s clear that you put a lot of thought and effort into each piece, and it certainly doesn’t go unnoticed.

  2. Manuel Avatar
    Manuel

    Your blog is a testament to your dedication to your craft. Your commitment to excellence is evident in every aspect of your writing. Thank you for being such a positive influence in the online community.

Leave a Reply

Your email address will not be published. Required fields are marked *