Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant alternatives for huge amount of arguments in class constructor [closed]

For example I have a class that builds the GUI, a class that handles all the events for the GUI and the main class that holds all the objects that are affected by the GUI-Objects (mostly sliders) and instances both the GUI-class and event-class.

Now the event-class's constructor has as arguments the GUI class and every object that is being changed by the GUI. These are quite allot of objects so the amount of arguments I have now are about 8 and still growing.

Is there a more elegant solution to my problem, 30 arguments simply doesn't feel right?

ps, I'd rather not combine classes because all three are quite big and would make everything much less readable.

like image 522
Timotheus Avatar asked Jun 18 '11 12:06

Timotheus


People also ask

How do you fix constructors with too many parameters?

Using a builder can solve the issue of having to many parameters in a constructor when all the fields are not mandatory. It also takes away the problems with having multiple constructors for different purposes. Note that a builder still should have a constructor with the mandatory fields that always needs to be set.

How many arguments should a constructor have?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.

How can we prevent constructor overloading?

Another option is to use a "parameter object" following the builder pattern - create another class whose sole purpose is to hold the data for the constructor parameters. This should be mutable, with setters for all of the different values.


1 Answers

Often a builder object with fluent syntax is used in such a case. You change:

new XYZEvent(a, null, null, b, null, c, d, null, null)

to

new XYZEventBuilder().setA(a).setB(b).setC(c).setD(d).build()
like image 129
Ben Voigt Avatar answered Sep 26 '22 15:09

Ben Voigt