Member-only story
SRP and SLAP: Keys to maintainable and readable code
In this post, we’ll take a look at two principles to apply to your code to make sure it’s as clear, readable, and maintainable as possible: SRP and SLAP.
Single responsibility principle (SRP)
The idea behind the single responsibility principle (SRP) is that every class, module, or function in a program should have one responsibility/purpose.
In other words, every class should have only one reason to change.
It is restating the importance of cohesion in code.
What violates SRP?
Let’s say a developer sees something like this in a user class:
changeAddress()
login()
logout()
Those three steps violate SRP. The functions should be separated.
You probably agree that long functions aren’t a good idea, but you’ve probably also seen them at work recently. So, how long is long? A thousand lines is definitely long, but 100? 25?
How long should be functions?
The answer is that there is no standard.However, if someone says that a function isn’t long if they can see the entire thing in one window, my question would be, What is your font size? :D
A way to rethink long functions
To demonstrate the single responsibility principle, let’s imagine two versions of a conversation with a colleague of yours — the one who writes long functions. The first version represents the SRP.
Conversation 1
Them: How was your weekend?
You: It was great, I went to the park on Saturday, and a movie on Sunday.
Them: Really? Which park?
You: The one by the main street.
Them: Is that family-friendly?
Conversation 2
Them: How was your weekend?
You: Oh, my weekend?! At 7 a.m. I took the car out of the garage, drove for 3 kilometers, turned right, went 4 more kilometers, and they had a detour. Can you imagine the mess they have on the roads? I turned around, then it started raining. There…