Skip to the workspace
Pebellslearn by building
Design Principles  ›  Lesson

Law of Demeter and Tell, Don't Ask

Law of Demeter 15 minAn object should only talk to its close collaborators and should tell them what to do instead of pulling out their data to decide for them.

software design architecture / Law of Demeter and Tell, Don't Ask

Explore each scene at your own pace.

01 · The rule

The rule

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 inside

The 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.