0

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.

Nemanja
  • 3,295
  • 11
  • 15
  • 1
    Where is the method `printToScreen` that's it's calling coming from? Based on those rules, that seems like the only potential outlier in the method body. – Tim Hunter Jul 17 '20 at 14:23
  • The printToScreen method is effectively called with the parameter acct.getBalance().printFormat(). Does that help? – mwarren Jul 17 '20 at 14:36
  • @TimHunter `printToScreen` method is declared in the same class, where the method `showBalance` is declared. According to law of Demeter it's allowed to call that method inside `showBalance` method. – Nemanja Jul 17 '20 at 14:37

1 Answers1

5

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());
Joni
  • 108,737
  • 14
  • 143
  • 193