Open/Closed — SOLID Principles — Part 2

Bob Godwin
2 min readMar 28, 2018

--

Can be extended but cannot be modified.

The Open Closed principle enforces a rule that a class can be easily extended but at the same time forbids any modification to it’s self. This principle highly draws it’s traits from the Decorator & Strategy pattern. The Decorator allows extension of behaviour dynamically or statically during runtime. It is often referred to as “the alternative to subclassing”, while the Strategy allows implementation of different algorithms interchangeable within the same family.

To understand this priciple let’s assume you have a requirement to build a team of developers that codes in different programming languages with different charateristics.

We could start by modelling a “Developer” as follows:

The above code defines what is required of a single developer within the team. We can then go ahead and create our Concrete Types that will conform to the “Developer” protocol or what is known as Interface in other programming languages.

With the help of “Strategy Pattern” we can compose our Concrete Types to produce “Interchangeable Algorithms” as mentioned earlier.

The Concrete Types is not fully conformed to the “Developer” protocol, but I just want to show the different flavours of composition that are available in Swift when it comes to extension. As a Swift developer you should always strive to favour extensions over subclassing.

The Concrete Types have now fully conformed to the “Developer” protocol and have different “Interchangeable Algorithms”.

Creating our team of engineers is pretty straight forward and we could model it as shown below:

As you can see the “Team” of developers where languages traits of all the developers are added at runtime, this is basically the Decorator Pattern mentioned earlier in play. Subclassing is totally avoided from our implementation. The Open/Close Principle is very effective when tracing bugs because it allows us to narrow the bug directly to function that is causing it.

This series is covering the SOLID principles using Swift Language with practical examples, the previous path was on Single Responsibility principles and the article covers the Liskov Substitution Principles. For the complete playground you can find it here on the github repository.

--

--