Open-Closed Principle
The open/closed principle states "software entities should be open for extension, but closed for modification".
Open for extension means that we should be able to add new features or components to the application without breaking existing code.
Closed for modification means that we should not introduce breaking changes to existing functionality.
Open-Closed Principle Example
Let’s take a look at an example in C#. Even if you are not a C# developer, with some OOP experience you will be able to follow along easily.
Let’s take a look how to write the below piece of code is violating this principle.
class Shapes { public Shapes() { Console.WriteLine("Class : Shapes"); } public void calculateCircleArea(double radius) { Console.WriteLine("Area of circle : " + ((3.14) * radius * radius).ToString()); } public void calculateRectangleArea(double length, double width) { Console.WriteLine("Area of rectangle : " + (length * width).ToString()); } }
You will notice how we are calculating area of different shapes. If we want to add a new shape then we need to update this class by adding a new method.
This violates the Open-Closed Principle.
Let’s correct it.
abstract class Shapes { public Shapes() { Console.WriteLine("Class : Shapes"); } public abstract double calculateArea(); } class Square : Shapes { public double length { get; set; } public double width { get; set; } public override double calculateArea() { return (length * width); } } class Circle : Shapes { public double radius { get; set; } public override double calculateArea() { return ((3.14) * radius * radius); } }
By using Inheritance and Polymorphism, it is now much easier to create extended behavior to the calculate area of different shapes. The cool thing is, that if we want to add new shapes then we can change/add the code without affecting any of these underlying pieces of behavior.