Oct 25
Let’s look at a method written in Java:
void printMyTransactions(MyAccount myAccount) {
Currency currency = myAccount.getCurrency();
printTransactions(currency.getFormat());
}
The problem with this method is that it shouldn’t know about the existence of Currency. In other words, our method doesn’t own an instance of Currency. The fact that MyAccount has a Currency in it should only be known to MyAccount itself. So it’s better to write this method as a delegation:
void printMyTransactions(MyAccount myAccount) {
myAccount.printTransactions();
}
This is the Law of Demeter for functions. It states that any method of an object should call only methods belonging to:
- itself
- any parameters that were passed in to the method
- any objects it created
- any directly held component objects
Following this law will help reduce the coupling in your program. I already see quite a few places where we can apply this law in our project.
“I already see quite a few places where we can apply this law in our project.”
Yeah, if by “quite a few” you mean “all over the place.”