CodePark/ questions / OOP principles & composition
START PRACTICINGPRACTICE
Backend question · Software design & patterns › OOP principles & composition

Which line violates the Law of Demeter?

const city = order.getCustomer().getAddress().getCity();

The line that breaks the rule is const city = order.getCustomer().getAddress().getCity();.

The
Law of Demeter says a method should only talk to:
• its own object

• that object's fields

• its parameters

• objects it creates


It should not talk to objects returned by those. This line reaches through the customer and then the address. So the code depends on the whole chain.


The fluent builder line
qb.where(a).andWhere(b).orderBy(c) is usually not a violation. Each call returns the same builder, so every call goes to one collaborator.