CatalinRadoi
6/9/2015 - 4:25 PM

The Law of Demeter.md

"Don't talk to strangers". It's the simple explanation of the Demeter's Law.

It's also known as the "Law of train wrecks" A -> B -> C

A should only know about it's closest "friends". It shouldn't access something from C. Instead, it should tell B to DO something, not to ask B about C.

TELL, DON'T ASK

A method M of an object O may only call the methods/params of the following:

  1. O itself
  2. M's parameters
  3. Any object CREATED within M
  4. O's direct component objects (O's instance variables)

Example:

public void ShowBallance(BankAccount account)
{
    Money amount = account.GetBallance();
    this.PrintToScreen(amount.PrintFormat());
}

This violates the low, because it can be written like: this.PrintToScreen(account.GetBallance().PrintFormat()); // it's an obvious violation

Code should be:

public void ShowBallance(BankAccount account)
{
  account.PrintBallance(); // TELL, DON'T ASK!
}