Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification." This means that new functionality can be added to a system without modifying existing code
Community
Why is OCP Important?
How does adhering to the Open-Closed Principle improve the extensibility and maintainability of your codebase?
Example in C#:
// Violation of OCP
public class Shape
{
public virtual double CalculateArea()
{
// Default implementation for rectangle
return Width * Height;
}
public int Width { get; set; }
public int Height { get; set; }
}
// Adhering to OCP
public abstract class Shape
{
public abstract double CalculateArea();
}
public class Rectangle : Shape
{
public override double CalculateArea()
{
return Width * Height;
}
public int Width { get; set; }
public int Height { get; set; }
}
public class Circle : Shape
{
public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
public int Radius { get; set; }
}
In the first example, adding a new shape (e.g., Circle) requires modifying the Shape class. In the second example, we use inheritance to extend the Shape class without modifying it. This makes the code more flexible and easier to maintain.
Design Patterns: Many design patterns, such as Strategy, State, and Template Method, are used to implement the Open-Closed Principle.
Polymorphism: Polymorphism is essential for OCP. It allows you to treat different objects (subclasses) as if they were the same type.
Interfaces: Interfaces can be used to define contracts that subclasses must implement, promoting flexibility and extensibility.
Effortless content and community for innovators and business minds
Members enjoy exclusive features! Create an account or sign in for free to comment, engage with the community, and earn reputation by helping others.
Create accountBuilding a Strong Foundation for Successful Business Solutions
Understanding the 'S' in SOLID