Skip to content
Home Sinan Eldem
Software

Open–Closed Principle

Sinan Eldem

• 3 min read

Open–Closed Principle

In this article, we'll cover the second of the SOLID principles. Wondering "What were those principles again?" Go ahead and check out the summary article.

Over an application's lifetime, far more time is spent adding to an existing codebase than constantly building new features from scratch. As you may already know, this can be a tedious and frustrating process. Every time you modify your code, you risk introducing new bugs or breaking existing functionality entirely. Ideally, we should be able to change our existing codebase as quickly and easily as we write brand-new code. If we design our application to follow the Open-Closed principle, we can do just that!

The Open-Closed principle of SOLID design states that code should be open for extension but closed for modification.

To demonstrate the Open-Closed principle, let's keep working with the OrderProcessor from the previous chapter. Consider the following section of this class's `process` method:

$recent = $this->orders->getRecentOrderCount($order->account);

if ($recent > 0)
{
    throw new Exception('Muhtemelen aynı sipariş ikilendi.');
}

This code is quite readable, and since we use dependency injection properly, it's easy to test. But what happens if our business rules around order validation change? What if we get new rules? In fact, what happens when we get many new rules as our business grows? Our `process` method will quickly turn into a hard-to-maintain spaghetti-code monster. Because this code has to change every time our business rules change, it is open for modification and therefore violates the Open-Closed principle. Remember, we want our code to be open for extension, not modification.

Instead of doing all of our order validation directly inside the process method, let's define a new interface: OrderValidator:

interface OrderValidatorInterface {
	public function validate(Order $order);
}

Next, let's define an implementation that protects against duplicate orders:

class RecentOrderValidator implements OrderValidatorInterface {

	public function __construct(OrderRepository $orders)
	{
		$this->orders = $orders;
	}

	public function validate(Order $order)
	{
		$recent = $this->orders->getRecentOrderCount($order->account);

		if ($recent > 0)
		{
        	throw new Exception('Muhtemelen aynı sipariş ikilendi.');
		}
	}

}

Great! Now we have a small, testable encapsulation of a single business rule. Next, let's create another implementation that checks whether the account has been suspended:

class SuspendedAccountValidator implememts OrderValidatorInterface {

	public function validate(Order $order)
	{
		if ($order->account->isSuspended())
		{
			throw new Exception("Askıya alınmış hesaplar sipariş veremez.")
		}
	}

}

Now that we have two different implementations of our OrderValidatorInterface contract, let's use them in the OrderProcessor. All we need to do is inject an array of validators into our processor instance, so we can easily add or remove validation rules as our codebase evolves.

class OrderProcessor {

    public function __construct(BillerInterface $biller,
                                OrderRepository $orders,
                                array $validators = array())
    {
        $this->biller = $biller;
        $this->orders = $orders;
        $this->validators = $validators;
    }

}

Then, in our process method, we can simply loop through the validators:

public function process(Order $order)
{
	foreach ($this->validators as $validator)
	{
		$validator->validate($order);
	}

	// Geçerli siparişi işle...
}

Finally, we'll register our OrderProcessor class in the application's IoC container:

App::bind('OrderProcessor', function()
{
	return new OrderProcessor(
		App::make('BillerInterface'),
		App::make('OrderRepository'),
		[
			App::make('RecentOrderValidator'),
			App::make('SuspendedAccountValidator'),
		],
	);
});

With these few changes, which took only minimal effort to build on our existing codebase, we can now add and remove validation rules without changing a single line of existing code. Each new validation rule is simply a new implementation of OrderValidatorInterface registered in the IoC container. Instead of unit testing a large, unwieldy process method, we can now test each validation rule in isolation. Our code is now open for extension but closed for modification.

Leaky Abstractions

Watch out for dependencies that leak implementation details. An implementation change in a dependency should not require any changes in the class consuming it. When the consuming class has to be changed, the dependency is said to be "leaking" implementation details. If your abstractions are leaky, the Open-Closed principle has most likely been broken.

Before we go any further, remember that this principle is not a law. It doesn't say that every piece of code in your application must be "plug-and-play". For example, a small application that fetches a few records from a MySQL database doesn't need to strictly adhere to every design principle you can think of. Don't guiltily apply a design principle blindly, since you'll likely end up with an over-engineered, unwieldy system. Keep in mind that many of these design principles were created to solve common architectural problems in large, massive applications. That said, don't use this paragraph as an excuse to be lazy!

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more