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.
The object
amt
is not created insideshowBalance
- you retrieve it with a method call togetBalance
.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: