Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long parameter list in constructor in Java [duplicate]

Possible Duplicate:
What's the best way to refactor a method that has too many (6+) parameters?

If a constructor has a long parameter list, should we consider it bad style and refactor it? If yes, how?

like image 938
BB. Avatar asked Jan 20 '11 13:01

BB.


2 Answers

Consider using a Builder. Instead of having a constructor where some of the parameters can be null:

Foo foo = new Foo(name, id, description, path, bar);

And instead of telescoping constructors - i.e. making one constructor for each combination of parameters, you can have:

Foo foo = new FooBuilder().setName(name).setPath(path).build();
like image 157
Bozho Avatar answered Nov 01 '22 12:11

Bozho


It may be an appropriate set of parameters, but a lot of the time my answer would be yes. Break the parameters into a logical subgroupings if they exist i.e. rather than creating a Car from many different parts, group some parts into an Engine object, some into a Chasis etc.

Alternatively, if some of those parameters are optional, make use of the builder pattern so that you only include them when necessary.

Ultimately, though, do whatever makes most sense for you and your domain.

like image 24
GaryF Avatar answered Nov 01 '22 14:11

GaryF