Law of Demeter and local variables inside function

144 Views Asked by At

I'm trying to understand Demeter's law. This example (taken from the book called 'Pragmatic programmer') confuses me.The task is to determine if the shown method call is allowed according to the Law of Demeter.

public void showBalance(BankAccount acct) {
Money amt = acct. getBalance() ;
printToScreen(amt .printFormat()) ;
}

In response to this task, it is written that it violates Demeter's law, but I don't undersand why? According to the Law of Demeter, a method M of object O should only call following methods:

  1. Methods of Object O itself (because you could talk with yourself)
  2. Methods of objects passed as arguments to M
  3. Methods of objects held in instance variable
  4. Methods of objects which are created locally in method M
  5. Methods of static fields

The object amt is created locally inside method showBalance(BankAccount acct) and we are calling method getBalance() on that object which is allowed according to rule number 4. This is what confuses me.

1

There are 1 best solutions below

1
On

The object amt is not created inside showBalance - you retrieve it with a method call to getBalance.

You can't get around Law of Demeter by just extracting values to local variables, it requires careful design. Your code is equivalent to this, which should be prohibited by LoD:

printToScreen(acct.getBalance().printFormat());