What are the SOLID principles, and how do you apply them to a small design?
The five SOLID principles are five rules about how classes should be related to each other. Each one solves a different problem, and each one is about making the code easy to change.
public class Main {
public static void main(String[] args) {
Invoice invoice = new Invoice(new PercentDiscount(10));
invoice.add(new Item("Book", 20.0));
System.out.println(invoice.total());
}
}
And here is the design that follows them.
// The interface. It says what a discount can do.
public interface Discount {
double applyTo(double amount);
}
// The implementations. Each one is small and does one thing.
public class PercentDiscount implements Discount {
private final double percent;
public PercentDiscount(double percent) {
this.percent = percent;
}
@Override
public double applyTo(double amount) {
return amount * (1 - percent / 100);
}
}
public class NoDiscount implements Discount {
@Override
public double applyTo(double amount) {
return amount;
}
}
// The class that uses it. It holds the discount as a field and
// never asks what kind of discount it is.
public class Invoice {
private final java.util.List<Item> items = new java.util.ArrayList<>();
private final Discount discount;
public Invoice(Discount discount) {
this.discount = discount;
}
public void add(Item item) {
items.add(item);
}
public double total() {
double sum = 0;
for (Item item : items) {
sum = sum + item.price();
}
return discount.applyTo(sum);
}
}
So here is where each principle shows up in that design.
the letter the name where it is in the code
----------- -------------------------- -----------------------------
S single responsibility Invoice only works out totals
O open closed a new Discount needs no change
to Invoice
L liskov substitution every Discount can be used
wherever a Discount is wanted
I interface segregation Discount has one method
D dependency inversion Invoice depends on the
Discount interface and not on
a concrete class
And there is one thing that is worth knowing about, and it is that these principles are about change. Each one says that one kind of change should not force another kind of change. So a new kind of discount should not mean editing the invoice, and a new way of storing the items should not mean editing the discount.
So the rule to remember is this. Each principle stops one kind of change from breaking another.
The next two questions in this topic are about a hierarchy that breaks one of them and about what each principle solves.