One of the first things we learn as software developers are that there can be multiple solutions to a problem, some more efficient than others.

But there is something that we must always keep constant when writing code and that is to try to keep it as understandable as possible not only so that if someone else takes the reins of your project it will be easy for them to adapt to it but for yourself since the 90 % of the time spent by a developer is reading their own code. But how we can make our code more understandable as we write them? this is where the SOLID Principles come in, of which in this case we will focus on the S (Single-responsibility principle).

The Single Responsibility Principle (SRP) can be summarized in a single sentence: “A class should have to take care of a single job for which it should have a single reason to change”, but what does this mean and why? It is important.

Basically what this phrase means is that we should never overload our classes, they should be dedicated solely and exclusively to one function, be it parsing information, performing I / O operations, etc. Therefore, when we are defining our classes during the development process, we must be careful when writing our classes, if we begin to note that it is performing operations that should not concern that class, we must separate these functions into classes that are dedicated only to it. For example, if you have a class that is responsible for accessing the information in the database but also makes requests to an API then we should separate this class into 2 and use an intermediate class as explained in the repository pattern that depends on both and decide from which of the 2 to extract the information.

Now the purpose of this principle is of the utmost importance because if we start to overload a class with a multitude of functions in such a way that our entire project depends on it at the moment that this class fails, our entire project will do so with it, as well as keeping a class like that is a nightmare.

In conclusion, keep your code clean and never overload your classes, your future self will thank you as well as saving you a ton of debugging time.

Posted by

Andrés Maldonado – Systems Engineer