Should I add a method / constructor argument for an object that can be requested from another argument

Assuming I have this:

public class A {
   private B b;

   public B getB() {
     return b;
   }
}

Now I have a class that needs both B. The problem is whether the constructor should accept only A, and then I will ask B from A, or if the constructor will request both A and B?

Should it be:

public MyClass(A a) {
  this.a = a;
  this.b = a.getB();
}

or that:

public MyClass(A a, B b) {
  this.a = a;
  this.b = b;
}

p / s: I think these are pretty unnecessary questions, but whatever.

p / p / s: Thinks it was a community wiki? However, I do not have sufficient permission.: /

+3
source share
7 answers

I think this is a great question! since there is a “contradiction” of good practice.

: " ( )" ( " " )

, , MyClass A.

, .

+2

MyClass B:

new MyClass(new A(),new B());

, MyClass B... , .

+1

, A B , MyClass B, A, . , B A. getB() A , . MyClass A B A.

, MyClass B A, . B, - , , MyClass. . : A getB() ?

+1

, - , , Car Engine, engine.getEngineParts().

class Car
class Engine
class EnginePart

, setter .

, , EnginePart Engine. , , EnginePart Engine, ,

EngineAssembler (Engine engine, EnginePart part) {
    engine.addPart(part);
}
0

. , A B.

, A ( )

0

, Object A, B setter A .

public class MyClass{
  A a;
  Myclass(A a){
  this.a = a;
}

public void doSomething()
{
System.out.println(a.getB());
}
}

MyClass can always work with only one instance variable. Because you can always get B with a.getB (). If B cannot be null, make sure you check the null value of B when it is running on it.

0
source

Is it possible to not pass B at all, but instead, so that MyClass talks to A whenever he needs to do something?

0
source

All Articles