Any time I see articles about Law of Demeter the author never seems to give a solid example of how to obey this law. They all explain what it is and show an example of breaking
The Law of Demeter itself doesn't present a methodology for good demand. At best, it's a useful heuristic for identifying potentially problematic areas of code. Deviations from the law can be considered a 'code smell'
It can have the tendency to widen the interfaces of your classes, since it results in proxy, or wrapper, methods to give you access to properties that are owned by internal objects. As a result, its advantages should be balanced against its disadvantages (of potentially creating unwieldy classes and module).
It is best applied as a tool to identify code that may need refactoring. However, a simple swap of methods from
a.x.getFoo()
to
a.getXFoo()
is following the letter of the law, without following the spirit (acknowledgements to @TedHopp for that point). Instead, you should be looking into what users are trying to do when they pierce a
's abstraction in order to get x
's foo
and define that method accordingly. It may not be a trivial task, but that's why we get paid the big bucks :)