Law of Demeter and Tell, Don't Ask
Shelfwise's label printer contains order.customer.address.city. When customers were allowed several addresses, Customer.address became a list, and the label printer broke, though nobody had touched it. The printer knew too much about objects it had no business knowing. Two closely related principles keep objects from reaching through each other.
The rule
Talk only to your friends, and tell them what to do.
Law of Demeter (the "principle of least knowledge"). A method should only call methods on:
- its own object (
self), - its arguments,
- objects it creates,
- its own fields.
It should not reach through those to their insides. A chain like order.customer.address.city couples the printer to Order, Customer and Address all at once.
# Reaching through
city = order.customer.address.city
# Asking the friend
city = order.shipping_city()Now only Order knows how a shipping city is found, and when addresses change, only Order changes.
Tell, Don't Ask. Do not pull data out of an object, make a decision, and push the result back in. Tell the object what you want, and let it decide using its own data.
# Asking, then deciding for it
if wallet.balance >= total:
wallet.balance -= total
else:
raise InsufficientFunds()
# Telling
wallet.pay(total) # checks and subtracts insideThe asking version spreads the wallet's rule into every caller, and one caller that forgets the check can overdraw the wallet. The telling version keeps the rule inside, which is encapsulation in action.
A note on dots: the Law is about reaching through objects, not about counting dots. A fluent chain on one object, like text.strip().lower(), is fine, because each call returns a plain value you are working on, not a stranger's internals.