DEV Community

Cover image for SOLID in Software Development - 2
ajay-8192
ajay-8192

Posted on • Updated on

SOLID in Software Development - 2

Open-Closed Principle (OCP)

The Open-Closed Principle (OCP) states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means that we should be able to add new functionality to our code without having to modify existing code.

Here is an example of how the OCP can be violated:

public class Shape {
    private String type;

    public Shape(String type) {
        this.type = type;
    }

    public double getArea() {
        if (type.equals("circle")) {
            return Math.PI * radius * radius;
        } else if (type.equals("rectangle")) {
            return length * width;
        } else {
            throw new IllegalArgumentException("Invalid shape type: " + type);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This Shape class has two types of shapes: circles and rectangles. If we want to add a new type of shape, such as a triangle, then we will need to modify the getArea method to handle the new shape. This violates the OCP because the getArea method should not be modified to handle new shapes.

A better way to design this code would be to use a strategy pattern:

public interface ShapeAreaCalculator {
    double getArea();
}

public class CircleAreaCalculator implements ShapeAreaCalculator {
    private double radius;

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

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

public class RectangleAreaCalculator implements ShapeAreaCalculator {
    private double length;
    private double width;

    public RectangleAreaCalculator(double length, double width)

{
        this.length = length;
        this.width = width;
    }

    @Override


public

double

getArea()

{
        return length * width;
    }
}

public class Shape {
    private String type;
    private ShapeAreaCalculator shapeAreaCalculator;

    public Shape(String type, ShapeAreaCalculator shapeAreaCalculator) {
        this.type = type;
        this.shapeAreaCalculator = shapeAreaCalculator;
    }

    public double getArea() {
        return shapeAreaCalculator.getArea();
    }
}
Enter fullscreen mode Exit fullscreen mode

This code follows the OCP because the Shape class is not modified to handle new shapes. Instead, we can create a new ShapeAreaCalculator implementation for each new type of shape.

***** More to Part 3 *****
**** 💻ALL THE BEST💻 ****

Top comments (0)