Single Responsibility Principle in Java

Previous
Next

In this tutorial, we will learn about single responsibility principle in java.It is one of SOLID principles and simplest design principle as well.

Single responsibility principle dictates that there should be only one reason to change the class.If you have more than one reason to change the class then refactor the class into multiple classes according to functionality.

We will understand with the help of a simple example.Let’s say you have ¬†Customer class as below.

Do you see the problem with the above class? Let’ see what can be the issue with above class.

  • If there is any change in the calculation of bill then we need to change Customer class.
  • If you want to add one more report type to generate, then we need to change Customer class.

If you notice, calculation of bill and report generation should not be the responsibility of Customer, we should create different classes for these functionalities.

Let’s see refactored class now.

Create a new class named BillCalculator and pass Customer object to it.This class will be responsible for calculation of the customer bill

Create a new class named ReportGenerator and pass Customer object to it.This class will be responsible for generation of the customer report

As you can see now if we need to change anything in bill calculation, we don’t need to modify customer class, we will make changes in BillCalculator class.
Similarly, If you want to add another reporting type, then you need to make changes in ReportGenerator class rather than Customer class.

That’s all about Single Responsibility Principle in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog