Tuesday, May 2, 2023

SOLID - Open Close Principal explanation with sample C# code

The Open-Closed Principle (OCP) is a principle in object-oriented programming that states that classes should be open for extension but closed for modification. In other words, we should be able to add new functionality to a class without changing its existing code.

Here is an example of how to implement the OCP in C#:
public abstract class Shape
{
    public abstract double Area();
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public override double Area()
    {
        return Width * Height;
    }
}

public class Circle : Shape
{
    public double Radius { get; set; }

    public override double Area()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}

public class AreaCalculator
{
    public double TotalArea(Shape[] shapes)
    {
        double area = 0;

        foreach (var shape in shapes)
        {
            area += shape.Area();
        }

        return area;
    }
}
In this example, we have an abstract base class called 'Shape' that defines the 'Area' method. We then have two concrete classes that inherit from 'Shape' called 'Rectangle' and 'Circle'. These classes implement the 'Area' method in their own way.

We also have a class called 'AreaCalculator' that has a method called 'TotalArea'. This method takes an array of 'Shape' objects and calculates the total area of all the shapes in the array.

By using the OCP, we can add new shapes to our program without having to modify the existing 'Shape', 'Rectangle', 'Circle', or 'AreaCalculator' classes. We can simply create a new class that inherits from 'Shape' and implement the 'Area' method in our own way.

Overall, adhering to the OCP helps us create code that is more flexible and easier to maintain over time. We can add new functionality to our program without having to change existing code, which reduces the risk of introducing bugs or breaking existing functionality.

No comments:

Post a Comment