Part 5 of 7 · 1 min read
The links in Java
Who creates the object tells you the link.
A habit that works well in code (common practice): look at who creates the object.
class TimeSlot {
private final int start, end;
TimeSlot(int start, int end) { this.start = start; this.end = end; }
}
class Room {
private final String id;
Room(String id) { this.id = id; }
}
class Booking {
private final Room room; // association: passed in, outlives the booking
private final TimeSlot slot; // composition: created and owned here
Booking(Room room, int start, int end) {
this.room = room;
this.slot = new TimeSlot(start, end);
}
boolean sameRoom(Room other) { return room == other; } // dependency on Room as a parameter
}
The Booking constructor receives a Room that already exists, so the booking only knows it. It creates its own TimeSlot, so it owns it. The method sameRoom uses a Room for one call only, which is a dependency. When the booking is discarded, the TimeSlot goes with it and the Room stays.
Two practical rules:
- Hold a reference only when it is needed over time. A dependency passed as a parameter is lighter than a field.
- Avoid two-way links unless both are needed. If Room also held a list of its bookings, the two classes would depend on each other, and keeping the two sides in step becomes the programmer's job.
Check yourself:
1. Which link is slot, and why?
2. Which link is room?
3. What is the risk of a two-way link?