Reputation: 239
Suppose I have a function which takes in a List of objects, something like:
class A{
C c;
C getC();
}
Class C{
boolean propBool;
boolean getPropBool();
}
public void someThing(List<A> lst){
for(A a : lst){
if(a.getC().getPropBool()){
//do some stuff
}
}
}
On face value, this looks like a violation of the Law of demeter since I am accessing A, then accesing the inner object C
, then inside C
I am accessing propBool
.
The problem is, i am not too sure how to rewrite this to not violate the law of demeter.
Writing a helper which takes in C seems extremely useless.
public boolean getPropBoolFRomC(C c){
return c.getPropBool();
}
Whats the approach here?
Upvotes: 2
Views: 235
Reputation: 719279
The Law of Demeter (LoD) is not really a law. It is actually just a design principle. It is generally helpful, but by no means universally applicable. You can ignore it if you think it is not applicable (or helpful) to your use-case. Nobody will take you to court for violating the LoD.
In your use-case, you would need to decide if C
is an implementation detail of A
or not, and whether it is a good thing to hide it. The Law of Demeter doesn't answer that question for you. You need to decide for yourself, according to the specific needs of your use-case.
However, if you decide that C
is an implementation detail of A
and that it should be hidden then the Law of Demeter says that you should implement something like the helper function. In this context it is not "extremely useless". It has a specific purpose ... which is to hide the implementation detail. I would write it like this:
public class A {
private C c;
private C getC() {...}
public getTheProperty() {
return this.getC().getPropBool();
}
}
class C {
private boolean propBool;
boolean getPropBool();
}
(This is one of those cases where you cannot have it both ways. Either the LoD applies and the helper is not useless, or it doesn't apply.)
Note that we cannot advise you on whether LoD should be applied here. Your example is too abstract. A valid judgement can only be made in the context of a realistic application design.
Upvotes: 1
Reputation: 8758
Depending on what you are doing in that if
you rewrite code like that
for (A a : lst) {
a.getC().doStuff();
}
And inside C.doStuff()
check that boolean and implement logic.
Upvotes: 0