Repaso
Español
Design & PracticesAdvancedDP-15

Which line violates the Law of Demeter ('talk only to your immediate friends')?

Options

  1. total = order.total() + shipping
  2. order.customer.address.city.upper() (Correct option)
  3. self.repo.save(order, commit=True)
  4. count = len(items) + len(extra)

Answer

order.customer.address.city.upper()

Why

The Law of Demeter says a method should talk to its direct collaborators, not reach through them into their internals.

order.customer.address.city means your code knows how Order, Customer and Address are built inside. If any of them changes, your code breaks.

Better: ask the nearest object for what you need, e.g. order.shipping_city().

Remember

Avoid long chains of dots into other objects' internals.

Key terms

Practice this question in Repaso