### Open Close Principle

Open Close Principle: Software entities (classes, modules, functions, etc.) should be open for extension but close for modification. We should write the class code in such a way if requirement changes every time then we don’t need to change class code.
Let’s take a simple example to calculating the area.
 public class RightAngle { public double Width { get; set; } public double Height { get; set; } }

Now I am calculating the area of Right angle. This is very simple to calculate area as below.
 public class AreaCalculator {     public double Area(RightAngle shapes)     {         double area = 0;         area = (shapes.Width*shapes.Height)/2;         return area;     } }

Now I wanted to extend this class to calculate area of rectangle as well. Now I will have to modify the AreaCalculator class. This is little complex to do as below.
 public class AreaCalculator {     public double Area(Object shapes)     {         double area = 0;         if (shapes.Equals("Rectangle"))         {             Rectangle rectangle = (Rectangle)shapes;             area = rectangle.Width*rectangle.Height;         }         else         {             RightAngle rightAngle = (RightAngle)shapes;             area = (rightAngle.Width * rightAngle.Height) / 2;         }                return area;     } }

Now I would like to add some more shapes like Circle and Square, I don’t think it is very difficult to add these shapes. You can just add the switch case or if and else if condition in Area method of above class. But here is the issue whenever then new requirement comes I have to change my class this means my AreaCalculator class is not closed for modification Also not open for extension. This is very simple example but in real scenarios this will be very difficult to modify the class as it will require whole application rebuilds and redeploy also again testing.
Now I am trying to write this class based on Open Closed Principle. I have created an interface Shape. Rectangle and Right-angle classes will implement this interface. You can also create an Abstract class in place of Interface.
 public interface Shape {     double Area(); } public class Rectangle : Shape {     public double Width { get; set; }     public double Height { get; set; }     public  double Area()     {         return Width*Height;     } } public class RightAngle : Shape {     public double Width { get; set; }     public double Height { get; set; }         public  double Area()     {         return (Width * Height)/2;     } } public class AreaCalculator {     public double Area(Shape shape)     {         double area = 0;         area = shape.Area();         return area;    }     }

In Above code AreaCalculator is closed for modification but it I open for calculating area of any shape. Now you will see in this case I have written little more code and taking more time but it is good for further extension.