SOLID Principles — Part 1

Bob Godwin
2 min readMar 23, 2018

--

Single Responsibility Principle

Single Responsibility Principle — SRP

So the Gang of Four laid the first foundation of OOP design patterns more than 2 decades ago, although it is outdated in my opinion, but it is still useful when striving to write clean code. This principle states that a class should do only one job! Yes this is the meaning of single responsibility and there is no need to sugar coat it. “A class = performs one operation” simple and stupid.

So let’s say we have a requirement that needs to enable/disable or switch on/off a service on a server and we want apply this principle to the core. We could start by having an abstract representation using a protocol to describe what the business logic should do in the first place as follows:

The “SwitchOn and SwitchOff” defines the intent succinctly, so let’s say we have a model that contains a “state” and it is represented by a “BoolConcrete Type, as shown below.

For us to strictly apply Single Responsibility Principle we need to find a way to turn on/off the “Switch class” without directly calling “func on()” or “func off()” from it. This is what the Gang of four was trying to teach us with this principle.

While the above code is totally correct but it is “anti-pattern. For us to be cohesive we need to perform these actions based on the given contract, which is through the Interface and not directly accessing the Concrete Type.

Here we’ve refactored the code and introduced an Interface that executes an operation independent of what it is going to execute. All we know is that it executes an operation.

One of the advantages of Single Responsibility Principle is readability, cohesiveness and testable code base. On the other hand this could lead to having a “ravioli” code base. As a developer you should always cut the middle ground on what makes sense.

This series is covering the SOLID principles using Swift Language with practical examples the next part continues here: Part 2 OPEN/CLOSED Principle

You can also find the complete playground here on the github repository

--

--