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 but that is easy.
There is probably lots of ways to obey this law (good design and planning being one) but in very simple terms would this be a way to obey it?
Let's say I have a class with these properties:
public class Band {
private Singer singer;
private Drummer drummer;
private Guitarist guitarist;
}
I am somewhere in the program and I have an instance of this Band
class and I want the guitarists name, what I usually see is something like:
guitaristName = band.getGuitarist().getName();
That one does not seem too bad as it is not going too deep in the chain but is Law of Demeter saying that maybe it should be done this way:
guitaristName = band.getGuitaristName();
and my Band
class has a method:
public String getGuitaristName() {
return guitarist.getName();
}
Is this how you are supposed to obey the law?
Thanks.
You are not applying LoD at the appropriate level: both Band
and Guitarist
should be considered a part of the same module and the dilemma you have shall be decided on the grounds of maximum convenience.
Your question is an example of a much wider problem, which I have frequently met in books on design patterns and similar: they try to explain wide-reaching principles, which concern the design of a complex system, on ridiculously undersized problems. The result is just reader's confusion.
Where you'd actually see this principle in effect is something like this: you are using AsyncHttpClient
, which is an abstraction built atop Netty
, which is an abstraction built atop Java NIO. Now, if AsyncHttpClient
's API forced you at some place to directly manage a Java NIO object, whose API is much more raw, and deals with concepts completely foreign to AsyncHttpClient
, that would be an example of breaking LoD.