DEV Community

Cover image for SRP for couples
detoix
detoix

Posted on

SRP for couples

Single Responsibility Principle is a well-recognized rule that all software developers (and, as you're going to see, others as well) should follow in order to make systems maintainable and easy to extend.

There are many definitions and ways to explain it. Here I'd like to lay out what I believe to be a comprehensive real-world explanation of how should this principle be applied. And to do that, we're going to visit a couple's bedroom.

Bedroom drawers

When two people live with each other, in their bedroom, there usually are drawers with underwear. And there is not one, but two of them. It's common sense, but let's spend some time to find out why is it so. Why are there 2 separate drawers and, particularly, why is their responsibility split like that?

Other setups

Let's ponder for a while and imagine that you're moving in with someone, and you need to find out how where to put your socks and underwear. Some of the possibilities are as follows:

  • Socks in one drawer, underwear in the other one
  • White in one drawer, colored in the other one
  • His in one drawer, hers in the other one

Problem setting

What we generally want to achieve when developing a working (software) system is loose coupling. In our example, we expect a solution that allows for maximum independence of both partners, so it is not acceptable that one person waits until the other one dresses up.

If we, for instance, split responsibilities with the second solution we've listed above, out actors will encounter a problem when one of them will look for white socks, whereas the other one will be waiting for their turn to pick theirs.

The principle

The only way to prove one solution better than other is to follow the Single Responsibility Principle, which states that "an entity should have only one reason to change".

This reason is that a person wants to get dressed. Putting both partners' socks in one drawer and underwear in the other one causes that for any drawer there are two reasons to change - it is that any of two partners wants to get something and it leads to obvious problems.

Conclusion

Design your systems like bedroom drawers: let your code areas change independently by different reasons and you will find out that it is nothing more than the same common sense that leads to putting underwear in bedroom drawings in this well-known way.

Top comments (1)

Collapse
 
terkwood profile image
Felix Terkhorn

Preach! 🌟 I have recently started writing more Godot and I think about this a lot - - if I'm not careful about applying SRP, it's gonna be painful to revisit a large (weakly typed!) code base after some time passes