Applying the open-closed principle to a simple factory

Fabio
Applying the open closed principle
2 min readFeb 27, 2019

I have been recently reading the book from Matthias Noback (“Principles of Package Design”) and found very useful to review (among others) the open/closed principle from SOLID.

This is an excerpt of the Wikipedia definition :

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification that is, such an entity can allow its behavior to be extended without modifying its source code.”

The keywords to keep in mind are extension and modification. The principle basically tells us that we should design classes in such a way that we can extend their behavior without modifying the code.

I then thought to share a recent simple case in which I had the opportunity to enforce the principle. I had a simple factory class which looked as follows:

The class is quite simple and backed by a unit test. But what if in a year from now another case has to be added? I decided to rewrite the class as follows:

As you can see now the class is open to be extended without any edits to its code, since the constructor now allows to dynamically inject the different cases:

public function __construct(array $activationDateCalculator) {
$this->activationDateCalculators = $activationDateCalculator;
}

And we can leverage a framework container (in this case a Laravel container) to perform the task:

Other notes:
- the container can be a good place to inject the different cases since as its stated in the book, it is better to “prefer immutable services

“after instantiation, it shouldn’t be possible to change any of a service’s properties “ (Matthias Noback)

- since now the factory class implements an interface, we are offering another point of flexibility, potentially allowing developers to completely rewrite the class (even if it is often less practical).

--

--