Skip to content

Open-Closed Principle: Adding New Behaviors Without Modifying Existing Code

On Clean Architecture: A Craftsman's Guide to Software Structure and Design by Robert C Martin

Reading Clean Architecture has given me several insights into the way I think about software development. One thing I particularly enjoy is how the book is structured: dedicating an entire chapter to each SOLID principle is an excellent way to introduce concepts that often seem abstract at first.

I’ve developed the habit of finishing a chapter and then revisiting its examples and scenarios, trying to understand not only the definition of a principle but also its practical application. At the moment, I’m diving deeper into the Open-Closed Principle (OCP).

For someone who has never encountered this principle before, the initial explanation can feel a bit overwhelming. At times, I felt like I was reading something written in a completely different language. However, as the concepts begin to connect with real-world situations, everything starts to make much more sense.

Among all SOLID principles, OCP caught my attention because it addresses a recurring challenge in software development: how to add new features without modifying behavior that is already working. The idea of extending a system without changing existing code reduces risks, makes applications easier to evolve, and contributes to building more stable software over time.

But what does it actually mean to be open for extension and closed for modification?


A Real-World Scenario

I believe concepts like this become easier to understand when we look at a real-world example.

Imagine we have a simple application responsible for processing payments for a cake shop. The system is already in production, running smoothly, and all payments are processed through a single payment gateway.

Everything seems fine until a new business requirement arrives:

From now on, orders above $1,000 must be processed through a different payment gateway that offers lower transaction fees for high-value purchases. All other orders should continue using the current gateway.

At first glance, this change seems simple.

However, it raises an important question:

How can we add this new behavior without changing what is already working?


The Problem

Let’s imagine an initial implementation for this scenario.

public class PaymentService
{
    public void ProcessPayment(decimal amount)
    {
        Console.WriteLine("Processing payment through the Primary Gateway");
    }
}

At this point, there is no problem.

There is only one business rule:

  • Every payment must be processed through the primary gateway.

The code is simple, easy to understand, and perfectly satisfies the current requirements.

However, after some time, the new requirement arrives.

A straightforward implementation might look like this:

public class PaymentService
{
    public void ProcessPayment(decimal amount)
    {
        if (amount > 1000)
        {
            Console.WriteLine("Processing payment through the Premium Gateway");
            return;
        }

        Console.WriteLine("Processing payment through the Primary Gateway");
    }
}

At first, everything seems solved.

The system still works, and the new rule has been successfully implemented.

But now another question appears.

What happens when a new requirement comes along?

Maybe international payments need to use a different gateway.

Maybe VIP customers require special processing.

Maybe a specific gateway should be used during promotional campaigns.

Very quickly, we could end up with something like this:

public class PaymentService
{
    public void ProcessPayment(
        decimal amount,
        bool isVip,
        bool isInternational)
    {
        if (isInternational)
        {
            Console.WriteLine("International Gateway");
        }
        else if (isVip)
        {
            Console.WriteLine("VIP Gateway");
        }
        else if (amount > 1000)
        {
            Console.WriteLine("Premium Gateway");
        }
        else
        {
            Console.WriteLine("Primary Gateway");
        }
    }
}

The problem is not that this code stopped working.

The problem is that every new rule requires modifying an existing class that has already been tested and validated.

In other words, the system grows through constant modifications to consolidated code.

This is exactly the type of scenario that the Open-Closed Principle aims to avoid.


Applying the Open-Closed Principle

One possible approach is to separate payment processing responsibilities into different strategies.

First, we create an abstraction that represents a payment gateway.

public interface IPaymentGateway
{
    void Process(decimal amount);
}

Now each gateway can implement its own behavior.

public class PrimaryGateway : IPaymentGateway
{
    public void Process(decimal amount)
    {
        Console.WriteLine("Primary Gateway");
    }
}
public class PremiumGateway : IPaymentGateway
{
    public void Process(decimal amount)
    {
        Console.WriteLine("Premium Gateway");
    }
}

The main service no longer needs to know implementation details and can work only with the abstraction.

public class PaymentService
{
    private readonly IPaymentGateway _paymentGateway;

    public PaymentService(IPaymentGateway paymentGateway)
    {
        _paymentGateway = paymentGateway;
    }

    public void ProcessPayment(decimal amount)
    {
        _paymentGateway.Process(amount);
    }
}

Now imagine a new requirement appears:

International customers must use a dedicated payment gateway.

To satisfy this requirement, we do not need to modify any existing gateway implementation.

We simply create a new one.

public class InternationalGateway : IPaymentGateway
{
    public void Process(decimal amount)
    {
        Console.WriteLine("International Gateway");
    }
}

Notice that the system’s behavior has been extended without modifying any existing implementation.

That is the essence of the Open-Closed Principle.


What I Learned Studying This Principle

Before studying the Open-Closed Principle, I used to see abstractions primarily as a way to organize code.

After diving deeper into the topic, I started realizing that abstractions can also serve as extension points within a system.

The goal is not to create interfaces for everything or anticipate problems that may never happen.

The goal is to identify areas of the system that are likely to change and design them in a way that allows new behaviors to be added with minimal impact.

In the end, OCP does not eliminate change.

It simply changes how we deal with it.

Instead of repeatedly modifying stable code, we expand the system through new implementations.

And the less we need to change code that is already working, the lower the risk of introducing regressions as the software evolves.

Get new notes by email

One email when I publish a note. Nothing else, and you can leave any time.