Open/Closed Principle (OCP)

Open/Closed Principle (OCP)

The Open/Closed Principle is one of the SOLID design principles, as described by Robert C. Martin. It emphasizes that software entities (such as classes, modules, or functions) should be open for extension but closed for modification1. In other words, we should design our code so that we can add new functionality without altering existing code.

The Original Definition

Bertrand Meyer initially introduced the Open/Closed Principle in 1988. He stated:

“Software entities should be open for extension, but closed for modification.”

However, Meyer proposed using inheritance to achieve this goal. According to his definition, a class is both closed (since it can be compiled, stored in a library, and used by client classes) and open (since new classes can inherit from it, adding new features). Unfortunately, inheritance can lead to tight coupling and maintenance challenges.

The Polymorphic Open/Closed Principle

Robert C. Martin and others redefined the principle to the Polymorphic Open/Closed Principle. Instead of relying on superclasses, this approach uses interfaces. Here’s how it works:

  1. Interfaces: Define interfaces that represent specific behaviors or contracts.
  2. Implementations: Provide different implementations of those interfaces.
  3. Substitution: You can easily substitute one implementation with another without changing the code that uses them.

Extension Methods: A Perfect Example

Now, let’s discuss why extension methods exemplify the OCP:

  • Definition: Extension methods allow us to add new functionality to existing types without modifying their source code.
  • Closed for Modification: The original type remains unchanged; we don’t need to alter it.
  • Open for Extension: We can extend the type by defining new methods elsewhere.

Consider this simple example using C# and the Strategy pattern:

C#

// Original class
public class PaymentProcessor
{
    // Existing code
}

// Extension method
public static class PaymentProcessorExtensions
{
    public static void ProcessPayment(this PaymentProcessor processor, PaymentStrategy strategy)
    {
        // New functionality
    }
}
        

AI-generated code. Review and use carefully. More info on FAQ.

In this scenario, the PaymentProcessor class is open for extension (via the extension method) but closed for modification. We can add new payment strategies without altering the original class2.

Remember, embracing the OCP leads to more maintainable, flexible, and scalable software. Extension methods are a powerful tool in achieving this goal! 🌟

!extension method is best example of open closed principle

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics