Video in progress
What is wrong with a chain like `order.getCustomer().getAddress().getCity()`?
This is a Law of Demeter violation: the code talks not only to its direct "friends" but also to their internal structure. As a result, the caller becomes tied to a whole graph of objects, and any internal change breaks it.
📖 Answer
The Law of Demeter in short: a method should only call methods of:
this;- its own parameters;
- objects it created itself;
- its own fields.
In order.getCustomer().getAddress().getCity(), the caller knows that an Order contains a Customer and that contains an Address. If the address is moved from Customer to DeliveryInfo tomorrow, every place where this chain is written has to change. On top of that there is the NPE risk: any link in the chain may be null.
The options:
// 1. ask for what you need
String city = order.deliveryCity();
// 2. hand the work to the object itself
BigDecimal fee = order.deliveryFee(tariffs);
But this is not a "count the dots" rule:
list.stream().filter(...).map(...).toList()is a fluent API, every step is the same abstraction, so there is no violation;- a builder chain is the same;
- DTOs/records are plain data carriers, so reading fields from them is fine.
The problem starts when the object is an owner of behavior and you reach into its internal structure. Before adding a delegating method like deliveryCity() each time, think: maybe the calculation itself should live inside Order.
Sign up to mark studied questions and save your progress.