Open/Closed Principle

Back to Index

Introduction

The Open/Closed Principle is a key concept in object-oriented programming. It states that software entities (such as classes, modules, or functions) should be open for extension but closed for modification. This means you can add new functionality without changing existing code.

Benefits

Example

Consider a class that calculates the area of different shapes:

class AreaCalculator {
    double calculateCircleArea(double radius) {
        return Math.PI * radius * radius;
    }

    double calculateRectangleArea(double length, double width) {
        return length * width;
    }
}
            

This violates the Open/Closed Principle because adding a new shape requires modifying the existing class. To adhere to the principle, use abstraction:

interface Shape {
    double calculateArea();
}

class Circle implements Shape {
    private double radius;

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

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

class Rectangle implements Shape {
    private double length, width;

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

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

class AreaCalculator {
    double calculateTotalArea(List shapes) {
        return shapes.stream().mapToDouble(Shape::calculateArea).sum();
    }
}
            

Takeaway

By following the Open/Closed Principle, you create systems that can grow and adapt without requiring changes to existing code, making your software more robust and maintainable.

Back to Index