Law of Demeter

Talk only to friends, not to strangers

Which methods can you call?

  1. The method's arguments
  2. The object itself
  3. Locally instantiated objects
  4. Object's attributes

An example

Paper boy, Customer and Wallet


class PaperBoy
  def collect_money(customer, amount)
    if customer.wallet.cash > amount
      customer.wallet.withdraw(amount)
    else
      come_back_later
    end
  end
end
  

class PaperBoy
  def collect_money(customer, amount)
    if customer.request_payment(amount)
      puts 'Thanks!'
    else
      come_back_later
    end
  end
end
  

class Customer
  def request_payment(amount)
    @wallet.withdraw(amount)
  end
end
  

class Wallet
  def withdraw(amount)
    return false if @balance < amount
    @balance -= amount
    true
  end
end
  

Counting dots...


# Not OK
customer.wallet.withdraw(amount)

# OK - but why?
Post.published.last_week