Open-Closed Principle (OCP) - [O]

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

Published a month ago Viewed 0 times

Why is OCP Important?

  • Maintainability: New features can be added without risking breaking existing code.
  • Flexibility: The system becomes more adaptable to change.
  • Testability: Changes are easier to test and isolate.

Key Question:

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.

Additional Considerations:

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

Join to unlock full access and engage

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 account

More posts from Bizznessia (Developers)

bizznessia.dev is a community where developers can learn business, collaborate with like-minded individuals, and turn their ideas into reality. We’re here to support you every step of the way in achieving your goals