The Open/Closed Principle is one of the SOLID principles in programming. It states that a class should be open for extension but closed for modification.
Here’s an explanation with a C# example.
Example: Calculating Area of Shapes (Without OCP)
using System;
using System.Collections.Generic;
public class AreaCalculator
{
public double CalculateTotalArea(List<Shape> shapes)
{
double totalArea = 0;
foreach (var shape in shapes)
{
if (shape is Circle)
{
totalArea += Math.PI * Math.Pow(((Circle)shape).Radius, 2);
}
else if (shape is Rectangle)
{
totalArea += ((Rectangle)shape).Width * ((Rectangle)shape).Height;
}
}
return totalArea;
}
}
public abstract class Shape { }
… Читати далі