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:
- Methods of Object O itself (because you could talk with yourself)
- Methods of objects passed as arguments to M
- Methods of objects held in instance variable
- Methods of objects which are created locally in method M
- 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.