Law Of Demeter

Sean Coates
Jul 27, 2017 · 1 min read

Avoid chaining a series of methods together.


So you’ve take a complex method and broken it up into a series of smaller methods. It is now tempting to replace the invocation of the method a series of methods that call each other.

orderPizza()->addExtraCheese()->withExpeditedShipping->andChargeMyDefaultCreditCard->excludeTax();

That’s far too much happening in one line. The law of Demeter says you should only have one arrow. You can create new methods that basiclaly invoke “a()->b()”. Or you can separate this up into multiple lines using local variables.

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 tax is excluded, why should that break the addition of extra cheese?

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.

Written by

Occasional posts from @fooyay about software engineering, crypto, finance, and more. https://about.me/fooyay (Content reflects my opinion and not my employer.)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade