Gather together the things that change for the same reasons. Separate those things that change for different reasons.
Robert C. Martin
Every function, class or module should have one responsibility and that responsibility should be encapsulated in it.
The code of a program should be organized into classes. Each class should have one clear goal. A class should contain methods that do similar things. This means that similar functions (doing similar tasks) should be grouped into one class.
Let’s look at an example. Below is a class that generates a report:
public class ReportGenerator {
// method prints the report
public void printReport (String reportId) {
System.out.println(generateReport(reportId));
}
// method generates the report based on the given ID
private String generateReport (String reportId) {
// some logic to generate the report
return wygenerowanyRaport;
}
}
public class Runner {
public static void main (String [] args) {
ReportGenerator generator = new ReportGenerator();
generator.printReport("123");
}
The class has two responsibilities. That means there are two possible reasons to change it:
The generateReport method is responsible for creating a report,
The printReport method is responsible for displaying a report
A class should have only one reason to change.
Robert C. Martin
Improved implementation
Let’s split this class into two separate classes.
The ReportGenerator class will now only be responsible for generating reports:
public class ReportGenerator {
// method generates the report based on the given ID
public String generateReport (String reportId) {
// some logic to generate the report
return generatedRaport;
}
}
And the ReportPrinter class will be responsible for printing reports:
public class ReportPrinter {
// method prints the report
public void printReport (String reportToPrint) {
System.out.println(reportToPrint);
}
}
public class Runner {
public static void main (String [] args) {
ReportGenerator generator = new ReportGenerator();
ReportPrinter printer = new ReportPrinter();
String generatedReport = generator.printReport("123");
printer.printReport(generatedReport);
}
Why to use the Single responsibility principle
Code written with the Single responsibility principle is easier to maintain. Functions, classes, and modules become smaller and more consistent. Is is less likely to introduce bugs when changing anything.
It’s also easier to reuse code. Functions, classes and modules are simpler, more readable, and less specific. The code is better organized and more modular.