Law of Demeter

The Law of Demeter, also known as “don’t talk to strangers” or the “principle of least knowledge,” was formulated to minimize the knowledge that any given object has about the overall system structure.

In practice, if object A has a reference to object B, and B has a reference to C, A should not call methods on C through B (like a.b.getC().doSomething()). A can talk to B, and B can talk to C, but A shouldn’t directly get involved with C.

This fosters loose coupling. If you break LoD, your code assumes the structure extends beyond its immediate neighbors. For example, if OrderProcessor does order.getCustomer().getAddress().getZipCode(), it knows that an Order has a Customer with an Address. If Customer is changed to have multiple addresses, OrderProcessor breaks. If instead Order had a method getShippingZip() that internally navigates its customer/address, OrderProcessor could call that and be oblivious to structural changes.

LoD aligns with information hiding: each object hides its internals and only exposes necessary interfaces.

  • An object should only call methods of: itself, its direct components, its function parameters, or objects it creates. It should not navigate through one object to reach another ('don't talk to strangers').
  • If object A only calls B (its immediate friend) and doesn't reach into B's internals (like C), then changes to C or removal of C don't affect A. Each class knows as little as possible about others, reducing the impact of changes
  • It often leads to adding wrapper methods or delegations. While that might increase the number of methods, it results in cleaner interactions.
添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论