3 ms·
Think about it this way. Your code says a.b().c().d(). But then you discover that 'a' actually has method d() whose implementation is "return this.b().c().d()"
by galaxyLogic 7y ago
Think about it this way. Your code says a.b().c().d(). But then you discover that 'a' actually has method d() whose implementation is "return this.b().c().d()". In other words
a.d() <=> a.b().c().d()
Which call should you make?
Obviously a.d(), not only because it is shorter but because it makes your code independent of the fact whether a.b() returns something that understands c() which returns d() whose result is what you want.
a.d() is better code then than a.b().c().d() because it makes fewer assumptions about the rest of the system.
Now assume such a.d() does NOT exist. Would it make sense to create it? Yes because THEN you will be able to write better code by more simply writing a.d() .
Now there is a cost to writing a new method a.d(). But typically that cost is not much because its implementation is simple "return this.b().c().d()" .
But then you realize b().c().d() should be replaced by b.d() to follow the Law of Demeter again. So you actually must pay the price of writing two new methods if you want to follow Demeter. Is it worth it? It depends on how much you value maintainablity vs. having to write less code right now.
My guess is that following Demeter is almost always better.