Chaining a series of methods together can increase dependencies on distant objects.
There are two ways to chain a series of methods together. One way is to break a complex method into smaller ones that can return the an object of the same class and thus continue to call methods without reaching outside of the class. This way, dependencies stay within the class. When methods change, the methods that depend on them are limited to the same class.
pizza = Pizza.newLarge.addExtraCheese.addTopping(Pepperoni).addTopping(Sausage).withCrispyCrust
On the other hand, if the methods in chain return different objects of different classes, then the chain creates dependencies on distant objects. This tight coupling creates problems because now the class has many more reasons to change.
candidate = pizza.shipmentAddress.city.mayor.party.leader
That’s far too much happening in one line. Why should the pizza class know how to find the party’s leader? If the Party class changes its method names, why should distant classes like Pizza need to be updated? Just because one *can* create amazing chains like this does not mean that one should.
The law of Demeter says you should only have one dot. This limits dependencies to one class away. It’s also related to the Single Responsibility Principle, in that a class that has to know the inner workings of distant classes simply knows too much.
The problem with the long chain of calls is that the code becomes brittle. Any change to any of the methods in the series could break the whole chain. If there is a change to the way the party’s leader is determined, why should that break the creation of a pizza shipment?
Said another way, you want to have your objects and methods loosely coupled. When you chain a lot of methods together, you become tightly coupled. Loosely coupled objects and relationships respond to change a lot better, making it far easier to improve later.
Finally although it’s called a “Law”, you should treat violations of the Law of Demeter as more of a code smell than an actual fault. There are times when chaining a couple methods together doesn’t cause a lot of harm. Just be aware that when you see the long chains, it’s a good opportunity to do some smart refactoring.