Video in progress
Which design rule does this code break, and what problem does it cause in production?
public BigDecimal discountFor(Order order) {
String city = order.getCustomer().getAddress().getCity().getName();
if (order.getCustomer().getLoyalty().getLevel() > 3 && "Toshkent".equals(city)) {
return order.getTotal().multiply(new BigDecimal("0.1"));
}
return BigDecimal.ZERO;
}
It breaks the Law of Demeter: the service reaches deep along a chain of objects and gets tied to a foreign structure. If any class in the chain changes, this code breaks, a null in the chain gives an NPE, and a test needs three mocks.
📖 Answer
The Law of Demeter in short: "only talk to your immediate friends". A method should call methods on its own fields, its parameters and objects it created, not on what is inside them.
What this costs in practice:
- Hidden dependency.
discountFornow knows the structure ofCustomer,Address,CityandLoyalty. If you turnAddressinto aList<Address>, the discount logic breaks. - NPE. If a customer without an address comes in, the stack trace doesn't immediately say which link was null (helpful NPE messages help, but the problem stays).
- Painful tests. You need deep stubs or four mocks.
The fix is to ask the owner:
public BigDecimal discountFor(Order order) {
Customer c = order.customer();
if (c.isLoyalAbove(3) && c.livesIn(City.TASHKENT)) {
return order.total().percent(10);
}
return BigDecimal.ZERO;
}
This is where people often go wrong in interviews: it's not a "count the dots" rule. A stream().filter().map() or a builder chain doesn't break Demeter, because they work on one object. Reaching inside is also normal for DTOs and records, since their job is exactly to expose data.
Sign up to mark studied questions and save your progress.