Sign in

Open-Closed Principle

What is the Open-Closed Principle?

The Open-Closed Principle is one of the SOLID principles that is used to help developers write more maintainable and extendable software. It was first introduced by Robert C. Martin in his article and he describes it as:

  • Closed for modification. The source code of a program should not change when the program changes its behaviours. No one should be allowed to make the source code changes.

Why should we use the Open-Closed Principle?

One benefit of using the Open-Closed Principle is that we do not have to reinvent the wheel if they can extend upon behaviours that have already been defined, hence this makes development much faster. Furthermore, if a feature implemented is no longer needed, then the changes can be easily reverted.

Example

class Shape {
public double calculateArea(Shape[] shapes) {
double area = 0;
for(Shape shape:shapes) {
if(shape instanceof Rectangle) {
//Calculate Area of Rectange
}
else if(shape instanceof Circle) {
//Calculate Area of Circle
}
}
return area;
}
}
class Rectangle extends Shape {
}

class Circle extends Shape {
}
abstract class Shape {	
abstract double area();
}

class Rectangle extends Shape {
@Override
double area() {
// Area implementation for Rectangle
return 0;
}
}

class Circle extends Shape {
@Override
double area() {
// Area implementation for Rectangle
return 0;
}
}

Conclusion

In conclusion, by using Open-Closed Principle, we can develop simpler and extensible components which are ready for change without breaking existing implementations.