iOS — Single responsibility principle by example

Adriatik Gashi
3 min readFeb 20, 2022

A class should have just one reason to change

The idea of Single Responsibility Principle(SRP) is to make every class responsible for a single part of the functionality provided by the software, and make the responsibility entirely encapsulated by the class. The goal of this principle is reduce complexity. It’s always good to follow the SRP principle but if you’re writing a very small program which has 200 lines of code, with a dozen of pretty methods you will be fine.

The real problems emerge when your program constantly grows and changes. At some point classes become so big that you can no longer remember their details. Code navigation slows down to a crawl, and you have to scan through whole classes or even an entire program to find specific things.

There is more: if a class does too many things, you have to change it every time one of these things changes. While doing that, you are risking breaking other parts of the class which you did not even intend to change. If you feel that it’s becoming hard to focus on specific aspects of the program one at a time, remember the single responsibility principle and check whether it’s time to divide some classes into small parts.

Example

Let’s say we have an employee class which has the data of the specific employee and also prints the timesheet report, at this point the employee class has several reasons to change. The first reason might be related to the main job of the class: managing employee data. However, there’s another reason: the format of the timesheet report may change over time, requiring you to change the code within the class.

So the current employee class contains several different behaviors.

Solve the problem by moving the behavior related to the formatting and printing timesheet reports into a separate class. This change lets you move other report-related stuff to the new class.

So after this change the extra behavior is in its own class.

This article is written based in Book “Dive into Design Patterns” by Alexander Shvets which I’m reading right now. Feel free to email me (hiadriatik@gmail.com) if you have any questions, challenging opportunities, or you just want to say hi.

Linkedin: https://www.linkedin.com/in/adriatikgashi

Finally, be sure to follow me so that you do not miss any new stories I publish.

--

--

Adriatik Gashi

Self-tought pragmatic programmer with main focus on mobile technologies.