Talk only to friends, not to strangers
Which methods can you call?
- The method's arguments
- The object itself
- Locally instantiated objects
- 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