Search code examples
coding-styledesign-principles

When is it reasonable to violate the Single Responsibility Principle?


After refactoring some service-layer classes in our java web application, i was asking myself at which point it is reasonable to stop adhering to the Single Responsibility Principle (SRP) and to keep the maintainability and readability of the code. Now I am asking you about your experience with this issue.

Example:

Assuming a UserManager class which does the following:

  1. finds users from a database
  2. creates new users
  3. manipulates existing users

Case A: Every of these three responsibilities consists of several methods which perform their tasks.

→ It would be clear for me to split it into three classes.

Case B: Every of these three responsibilities consists of only one method.

What would you suggest in this case? Should this be separated into three tiny classes or left in the UserManager class?


Solution

  • In my opinion, SRP as related to OOP means that state and behavior related to a particular object or entity should all be within a single class. Thus, my opinion is that you would want to keep all methods related to users in a single class, regardless of how many methods there are or how many are needed to carry out a particular task.

    The point of SRP (as I see it) is to make sure that you don't have domain objects manipulating one another. In other words, if you (hypothetically) had another class called AccountManager, then that class should not have any operation that manipulates a User object directly - as this would violate SRP. Rather, the AccountManager class would need to rely upon the UserManager class to handle any/all user manipulation.