The Single Responsibility Principle (SRP)

A class should have only one reason to change.

This principle is one of the simplest of the principles, yet the easiest to get confused about, mostly because of its name.

As mentioned in the book, Agile Software Development: Principles, Patterns, and Practices, a responsibility, in the context of the SRP, is a reason for a change. That is when you change a class, and if you can think of another reason to change it separately, such as at a different time, then that class violates the SRP.

Another interpretation is that responsibility is an axis of change. Inside a class, all of the changes should occur around a central point or a continuum. You can think of a class as a discussion room. In one room, people are talking about hobbies, such as hiking, skiing, diving, and playing football how they like it. And then someone mentions watching movies, and suddenly several people start to have an intense discussion about what movies they like the best, who their favorite characters are, and the details of the scenes in those movies. And at that point, it would be better to divide the group into two different rooms; one continues talking about hobbies and the other discusses movies. In this way, the discussion of either group won't be affected by the other group. In this metaphor, the topic hobbies are the axis of change.

As Martin said: An axis of change is an axis of change only if the changes actually occur.

So, if there is no intense discussion of movies but only a brief mention of them, then there is no reason to move those people to another discussion room.

Because of the name of this principle, it is easy to think that each class should do one thing and one thing only. If we follow that interpretation when we design classes, we will add needless complexity into the design because we will destroy the cohesion of a class, which has its code bound together closely for a single responsibility, even though that class seems to be doing different things. It will also decrease the readability of the code because you will need to jump between different, smaller classes to link the fragments to understand the logic.

As a matter of fact, there is a principle saying that one method should do one, and only one, thing. However, that is for refactoring large methods into smaller ones, and it should be used at low-level design, which is the implementation level design.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.32.222