Spis Treści
Some theory
The first of the principles behind the letter S, abbreviated as SOLID, is the title Single Responsibility Principle. Its definition can be presented as follows:
There shouldn't be more than one reason for a class or method to exist
Sample code
Since this definition is simple enough, I will now show how easy it is to break this rule, and how it should be avoided in a specific situation. An example is the Report class, which handles functions related to reporting some data from the system.
public class Report {
private String reportData1, reportData2;
private String completeReport;
public Report(String reportData1, String reportData2) {
this.reportData1 = reportData1;
this.reportData2 = reportData2;
}
public void generateReport(){
completeReport = reportData1 + reportData2;
}
public void printReport(){
System.out.println(completeReport);
}
}
Note that this class aims to combine two fields with data in order to create a report and print it. And here comes the crux of the problem, i.e. breaking the rule. In addition to generating the report, the class is also responsible for printing it. In order for the implementation to comply with the principle of one responsibility, the code should look like this:
public class Report {
private String reportData1, reportData2;
private String completeReport;
public Report(String reportData1, String reportData2) {
this.reportData1 = reportData1;
this.reportData2 = reportData2;
}
public String getCompleteReport() {
return completeReport;
}
public void generateReport(){
completeReport = reportData1 + reportData2;
}
}
public class Printer {
public String textToPrint;
public Printer(String textToPrint) {
this.textToPrint = textToPrint;
}
public void printReport() {
System.out.println(textToPrint);
}
}
We have separated a new Printer class from the Report class, the principle of which is to print the report only. Remember that writing text to the console is just an example. The actual implementation of printing would certainly be more complicated.
Summary
Applying the single responsibility principle seems quite simple and obvious, but in practice we often think that we will save time by combining different responsibilities into one class or method. However, after some time it may turn out that the class functionality should be used elsewhere. Then we will have to refactor the class and extract the selected functionality from it.
Pingback: SOLID - podstawa programowania obiektowego – Wojciech Siwek
Comments are closed.