AlgoViz

Law of Demeter

medium 40 min

Talk to your own parts and to what you were handed, and not to the parts inside them.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:53

See it run

Objects at run time: who speaks to whom, and who must know about whom.

Operations

A hand in the pocket

The stall takes the money itself. Watch the purse's rule being skipped.

Step 1 of 5

Two objects meet

stallStalltill0samCustomerpays withpursepursePursecents500

The stall was handed a customer. The purse is the customer's own part.

Step 1: Two objects meet

class Stall:    def sell(self, customer, price):        customer.purse.cents -= price        self.till += pricesam = Customer(Purse(500))stall.sell(sam, 300)stall.sell(sam, 300)
Good for
Nothing that lasts
Costs
Every seller knows purses
Types the stall knows
2

Look for a minus sign on somebody else's field.

In the real world

The same law of demeter doing real jobs. Pick one and step through it.

Four changes, two designs. The last row is the price.

Step 1 of 4

A purse may not be negative

With chainsWith the law
no negativeall sellersPurse only
gift address
cards
new question

With chains each seller has to add the check.

Step 1: A purse may not be negative

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Cutting the chain into lines

    major

    The method still knows every type.

    Wrong
    c = order.customera = c.addresscity = a.city
    Right
    city = order.shipping_city()
  • Changing a stranger's field

    critical

    No rule of the owner runs.

    Wrong
    customer.purse.cents -= price
    Right
    ok = customer.pay(price)
  • A getter for a part

    major

    It opens the door again for everybody.

    Wrong
    def payment_method(self):    return self._method
    Right
    def payment_label(self):    return self._method.label()
  • Counting dots

    minor

    A fluent chain needs knowledge of one type.

    Wrong
    # "too many dots"a = words.filter(f)b = a.map(g)
    Right
    words.filter(f).map(g)
  • Forwarding everything

    major

    The order can suddenly close accounts.

    Wrong
    def __getattr__(self, name):    return getattr(self._customer, name)
    Right
    def shipping_city(self):    return self._customer.shipping_city()
  • One query per polite call

    major

    Fifty orders, fifty queries, and nobody sees them.

    Wrong
    [o.shipping_city() for o in orders]
    Right
    book.shipping_cities()   # loads once

Interview tips

  • Name the friends

    • Self
    • Parameters
    • Any object I make
    • My parts
  • Ask what for

    • Does the caller decide with it?
    • Then move the decision
    • Else delegate or pass the value
  • Know the exceptions

    • Fluent chains
    • Plain data
    • Parse outside data once
  • Mind the price

    • Group values by purpose
    • Narrow interfaces
    • Batch for lists