Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor requiring many input arguments

My question concerns constructors in java. I've learnt that we should minimize the number of arguments to method including constructor. So if I have a class with requires a lot of input arguments to be created how do I best go about this. Should I

A) Include them all in the constructor method signature:

Example:

public MyClass(SomeThing A, Vector v, OtherThing B, int number.. etc.){
      // construct
}

..

MyClass c= new MyClass(..);

c.doSomethingWithAllYouGot();

B) Can I construct only very little and then require the object user to add things before calling specific methods

public MyClass(SomeThing A){
      // construct
}

..

MyClass c=new MyClass(A);

c.attributeVector(v);
c.connectTo(B);
c.setNumber(n);
// etc.

c.doSomethingWithAllYouGot();

The second variant seems more elegant and clean but allows for more errors if the class is incorrectly used.

Or is there a problem with the the design of the class if it has too many input arguments?

like image 269
Flying Swissman Avatar asked Oct 20 '25 01:10

Flying Swissman


1 Answers

If there are really that many parameters, it could that your class is trying to be too many things at the same time. Take this as a hint that it could be broken down into smaller classes.

Alternatively, you could make the constructor package private, and use a builder in the same package to instantiate it.

like image 189
Frédéric Dumont Avatar answered Oct 21 '25 15:10

Frédéric Dumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!