Sobes.tech
Junior

What does the letter 'O' mean in the SOLID principles?

sobes.tech AI

Answer from AI

The letter 'O' in SOLID principles stands for the Open/Closed Principle.

It is formulated as: software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

This means that:

  • New behavior can be added by extending existing classes, for example, through inheritance or composition.
  • Existing code should not be changed to add new behavior. Changing existing code increases the risk of introducing errors into already working parts of the system.

Example:

Without adhering to OCP:

class Shape {
    String type;

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

class AreaCalculator {
    public double calculateArea(Shape shape) {
        if (shape.type.equals("circle")) {
            // calculate circle area
            return 0; // placeholder
        } else if (shape.type.equals("rectangle")) {
            // calculate rectangle area
            return 0; // placeholder
        }
        // Adding a new shape type would require changing this method
        return 0;
    }
}

With adherence to OCP:

interface Shape {
    double calculateArea();
}

class Circle implements Shape {
    // fields and constructor
    @Override
    public double calculateArea() {
        // calculate circle area
        return 0; // placeholder
    }
}

class Rectangle implements Shape {
    // fields and constructor
    @Override
    public double calculateArea() {
        // calculate rectangle area
        return 0; // placeholder
    }
}

class AreaCalculator {
    public double calculateArea(Shape shape) {
        // Method is closed for modification.
        // Adding a new shape type (implementing Shape) does not require changing this method.
        return shape.calculateArea();
    }
}