Rules of Thumb?

If you cannot come up with a meaningful name for your class focused on single responsibility, then it's probably doing too much.

Every object in our web application should have a single responsibility, and all object's services should be focused on carrying that single responsibility(SRP).

If you put more than one functionality in one Class in Java it introduces coupling between two functionality and even if you change one functionality there is a chance you broke coupled functionality, which requires another round of testing to avoid any surprise on the production environment.

Single Responsibility Principle Example

Let's see bad code design then we will see how to improve it using this principle.

In this example, we have a sample User Registration example.

When user register to the System then System will send mail t the user for verification.

Bad code design

First, let's see "bad" design and implementation. In bad design shows the functionalities like save user to the database and sending mail to user email address for verification mixed in a single class.

Below is an example which violates the Single Responsibility Principle.

Note that in above code, the User services and Email services are combined in a single class and hence it violates the Single Responsibility Principle.

Good code design

Let's refactor the code to make "good" design using SRP?

According to this principle, we need to separate out email functionality and its responsibility should be entirely encapsulated by the class. Below is an example to demonstrate the Single Responsibility Principle.

Note that in the above code, the responsibility of EmailService is separated from UserService so now UserService does its responsibility related user operations and EmailService does it's responsibility related email operations.

Do comment if you like this post or give us a suggestion if any improvements needed.