But Sometimes Ask
Of course we don't "tell" everything;1 we "ask" when getting information from values and collections, or when using a factory to create new objects. Occasionally, we also ask objects about their state when searching or filtering, but we still want to maintain expressiveness and avoid "train wrecks."
For example (to continue with the metaphor), if we naively wanted to spread reserved seats out across the whole of a train, we might start with something like:
public class Train { private final List<Carriage> carriages [...] private int percentReservedBarrier = 70; public void reserveSeats(ReservationRequest request) { for (Carriage carriage : carriages) { if (carriage.getSeats().getPercentReserved() < percentReservedBarrier) { request.reserveSeatsIn(carriage); return; } } request.cannotFindSeats(); } }
We shouldn't expose the internal structure of Carriage to implement this, not least because there may be different types of carriages within a train. Instead, we should ask the question we really want answered, instead of asking for the information to help us figure out the answer ourselves:
public void reserveSeats(ReservationRequest request) { for (Carriage carriage : carriages) { if (carriage.hasSeatsAvailableWithin(percentReservedBarrier)) { request.reserveSeatsIn(carriage); return; } } request.cannotFindSeats(); }
Adding a query method moves the behavior to the most appropriate object, gives it an explanatory name, and makes it easier to test.
We try to be sparing with queries on objects (as opposed to values) because they can allow information to "leak" out of the object, making the system a little bit more rigid. At a minimum, we make a point of writing queries that describe the intention of the calling object, not just the implementation.