Assuming that I have this:
public class A {
private B b;
public B getB() {
return b;
}
}
Now, I have a class that needs A and B. The questions is, should the constructor be accepting only A, and I would then query B from A, or should the constructor be asking for both A and B?
Should it be this:
public MyClass(A a) {
this.a = a;
this.b = a.getB();
}
or this:
public MyClass(A a, B b) {
this.a = a;
this.b = b;
}
p/s: I think this is a rather noobish questions, but whatever.
p/p/s: Thinks this should have been a community wiki? I don’t have enough permission though. :/
I think it’s an excellent question! as there’s a “contradiction” of good practices.
The first solution applies the rule: “try to pass the least number of parameters to a method (or constructor)” (Robert C martin mentions this rule in his book Clean Code)
The second snippet follows the rule of Law of Demeter, which says That MyClass should know as little as possible about A.
Personally I would go with the second option, but in some scenarios I might go for the first one.