I. Single Responsibility Principle in Swift

Rafael Asencio
2 min readApr 15, 2021

You’ve probably heard of the SOLID principles, but what exactly do they mean?

We are going to explain what SOLID means and we will talk about the first principle putting it into practice.

SOLID are a series of criteria that help us detect bad software design and prevent bad practices. Therefore, it helps us to have a less rigid and more flexible system so that in any new change we don’t have a cascade effect on the rest of the components. It also provides us with greater mobility to be able to reuse the code and that our components are less coupled with each other, being at the same time more testable.

SOLID is an acronym that comes from the 5 principles. Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion. In this post we will deal with the first of them

Single responsibility: tells us that each type must have a well-defined responsibility, which means to have a responsibility per class. So instead of modifying a large monolithic component, we can isolate the changes into smaller units. being able to carry out tests in a simpler way since we can mock up certain classes and focus on one in particular.

Let’s say we have a class called ShopManager that is responsible of fetch product stock, save orders and convert currencies

If we apply the principle of responsibility, we will have each separate responsibility in each class, having in this case 3 different classes. the first one responsible for network functionality, another class to manage persistence, and last one for performing currency conversions

In this way, by having smaller code units, we can make changes or fix bugs easier than if we had a large monolith component.

I hope it helped to solve your possible doubts and that you have enjoyed.

Stay tuned for the following principles 😉

Happy coding!👨‍💻

--

--