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 { }
public class Circle : Shape
{
public double Radius { get; set; }
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
}
In this example, every time a new shape type is added (for example, Triangle, Square, etc.), the AreaCalculator
class must be modified. This violates the Open/Closed Principle because the class is open to modification rather than being closed.
Перекладено з: Open/Closed Principle (OCP)