Open-Closed Principle

Open-Closed Principle (OCP)

In this tutorial, we are going to discuss Open-Closed Principle (OCP) in SOLID Principles. OCP is the second principle which we should keep in mind while designing our application.

Open-Closed Principle

This principle states that “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” which means you should be able to extend a class behavior, without modifying it.

“Open to extension” means that you should design your classes so that new functionality can be added as new requirements are generated. “Closed for modification” means that once you have developed a class you should never modify it, except to correct bugs.

Suppose developer X needs to release an update for a library or framework and developer Y wants some modification or add some feature on that, then developer Y is allowed to extend the existing class created by developer X, but developer Y is not supposed to modify the class directly.

These two parts of the principle appear to be contradictory. However, if you correctly structure classes and their dependencies, you can add functionality without editing existing source code.

Generally, you achieve this by referring to abstractions for dependencies, such as interfaces or abstract classes, rather than concrete classes. We can add Functionality by creating new classes that implement the interfaces.

So applying Open-Closed principle to your applications limits the need to change source code once it has been written, tested, and debugged. This reduces the risk of introducing new bugs to existing code, leading to more robust software.

Let’s understand this principle through an Vehicle example. Consider the below method of the class VehicleWheelCalculations

public class VehicleWheelCalculations {
    public int getWheelsCount(Vehicle v) {
        if (v instanceof Car) {
            return 4;
        } else if (v instanceof Bike) {
            return 2;
        }
    }
}

Suppose we now want to add another subclass called Bus. We would have to modify the above class by adding another if statement, which goes against the Open-Closed Principle.

A better approach would be for the sub classes Car and Bus to override the getWheelsCount method:

public interface Vehicle {
    public int getWheelsCount();
}
public class Car extends Vehicle {
    public int getWheelsCount() {
        return 4;
    }
}
public class Bike extends Vehicle {
    public int getWheelsCount() {
        return 2;
    }
}
public class Bus extends Vehicle {
    public int getWheelsCount() {
        return 6;
    }
}

Adding another Vehicle type is as simple as making another subclass and implementing from the Vehicle interface.

Hence, we have achieved the goal of the open-closed principle by making another subclass and implementing from the Vehicle interface.

Open-Closed Principle
Scroll to top