How do the SOLID principles show up in ordinary Java code, with a worked example?
They are five short rules, and they all show up in ordinary Java code.
Single responsibility says that a class should have one reason to change. Open for extension, closed for modification says that you should be able to add a new kind of thing without editing the code that uses the old ones. Liskov substitution says that a subclass must be usable wherever its parent is. Interface segregation says that a small interface is better than a big one. And dependency inversion says that your code should depend on interfaces and not on concrete classes.
import java.util.List;
public class Main {
public static void main(String[] args) {
Report report = new Report(new SalesBook(), new ScreenPrinter());
report.print();
}
}
// Single responsibility: this class only turns numbers into a report.
class Report {
private final SalesBook book;
private final Printer printer;
Report(SalesBook book, Printer printer) {
this.book = book;
this.printer = printer;
}
void print() {
this.printer.print(this.book.total());
}
}
// Dependency inversion: the report depends on the interface.
interface Printer {
void print(int value);
}
class ScreenPrinter implements Printer {
public void print(int value) {
System.out.println("the total is " + value);
}
}
interface SalesBook {
int total();
}
class SalesBook implements SalesBook {
public int total() {
return 4200;
}
}
So how do they show up in real code? The dependency inversion one is the easiest to spot. If your class holds a concrete class, then it is tied to that class. If it holds an interface, then the caller decides which one it gets, and your class can be tested with a fake.
The open for extension one is the second easiest. If you add a new kind of payment, and you have to edit the service class to add a branch, then the service class is not open for extension. If you add a new class that implements the strategy interface and change one line at the point where it is created, then it is.
The next question in this topic looks at the difference between the first two and how they work together.