SOLID Design Principles — The (S)ingle Responsibility Principle

Luke Wickens
2 min readJan 31, 2021
Photo by Christopher Gower on Unsplash

After seeing SOLID plastered over the internet and only having a broad understanding over what this means, I have decided to take a closer look at what components make up SOLID design and the benefits associated with implementing each.

This article, as mentioned in the title, will be concerned with the ‘S’ in SOLID, The Single Responsibility Principle (SRP).

A class should have one, and only one reason to change — Robert C. Martin

Essentially the idea of SRP is that a piece of code, whether that be a class, function/method or microservices, should have no more than one responsibility. For example, if we have a function that calculates two numbers, it should not also print out the result of the calculation. Therefore reducing the amount of processes that it has responsibility for to one.

The Benefits of Using SRP

The argument for using SRP is quite straightforward: it makes the code you write easier to implement and reduces the potential for unexpected side-effects resulting from future changes.

Having easily readable and explainable code in the long run is a necessity that should not be overlooked. This is where, in my opinion, SRP provides the most benefit. If you are reading someone else's code, and a class has multiple responsibilities and interacts with other classes that also have many different responsibilities, it is difficult to follow and understand exactly what is happening. Especially for a new developer working with legacy systems without proper or sufficient documentation. With SRP, it should make code easier to read and explain, as it should only have one purpose. This is also great for testing as they should be easier to write and therefore should be easier to understand.

An easy way to develop your code using SRP, when thinking about what a class/function does, if you have to use the word ‘and’ then your class/function probably has more than one responsibility. It is then best to go back to the drawing board and reassess your thinking for this particular piece of code.

Summary

SRP is the most commonly used design principles in OOP.

The correct procedure for follow this principle is that your class is not allowed to have more than one responsibility. This avoids any unnecessary, technical coupling between responsibilities and lowers the probability that you will need to re-write multiple classes if a requirement for the piece of software changes. It also reduces the complexity of each change because it, in theory, should have a minimal amount of dependent classes that are affected by it.

--

--