Concept
Build classes out of other objects they hold and delegate to, instead of extending them. Composition keeps each class focused and lets you swap parts, including in tests.
The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.
A few lines that show Composition doing its job.
public class OrderService {
private final OrderRepository orders;
private final PaymentGateway payments;
private final Clock clock;
public OrderService(OrderRepository orders, PaymentGateway payments, Clock clock) {
this.orders = orders; this.payments = payments; this.clock = clock;
}
public Receipt place(Order order) {
var charge = payments.charge(order.total());
return orders.save(order.paidAt(clock.instant(), charge));
}
}Extending a class to borrow one method, such as class UserCache extends HashMap. Every HashMap method becomes part of your API, and a change in the parent can break you.
Your roadmap puts these before Composition, unless you already know them.
Once a session shows you understand Composition, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.
Topics that build on Composition.