Long list of options in constructor in Java

Possible duplicate:
What is the best way to refactor a method with too many (6+) parameters?

If the constructor has a long list of parameters, should you consider it a bad style and reorganize it? If so, how?

+4
source share
3 answers

It may be a suitable set of parameters, but many times my answer would be yes. Divide the parameters into logical subgroups, if they exist, and do not create a car from different parts, group some parts into an Engine object, some into Chasis, etc.

Alternatively, if some of these options are optional, use the builder pattern to include them only if necessary.

Ultimately, do what makes sense for you and your domain.

+3
source

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

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

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

 Foo foo = new FooBuilder().setName(name).setPath(path).build(); 
+11
source

Source: https://habr.com/ru/post/1336314/


All Articles