Card 02/ 08
All 8 cards
ExampleDifficulty: Intermediate1 min
An Invoice That Can Be Sorted Because It Says It Can Be Compared
A list of invoices, sorted by a method nobody wrote for invoices. The sorting code is decades old and has never seen this class.
class Invoice implements Comparable<Invoice> {
LocalDate due;
@Override
public int compareTo(Invoice other) {
return due.compareTo(other.due);
}
}List<Invoice> invoices = new ArrayList<>(loadInvoices());
Collections.sort(invoices);Collections.sort knows nothing about invoices, due dates or billing. It knows that whatever it has been handed implements Comparable, so each element can answer one question: are you before or after this other one.
What to notice is the direction of the dependency. The library did not have to be changed to support Invoice; Invoice declared that it meets a capability the library already required. New code plugs into old code, which is the opposite of how it usually goes.