Adam Alyyan
Adam Alyyan

Reputation: 420

Constructor with many required parameters

If I have a constructor for an immutable object that requires several (4+ parameters), is having a single constructor with all the required parameters the correct approach?

I feel this becomes a candidate for the Builder pattern, but I also feel like shying away from it since the parameters are required, and a Builder seems more appropriate when you get to pick and choose.

The example in my mind is a model object that does not change once created.

Upvotes: 3

Views: 1403

Answers (2)

K Erlandsson
K Erlandsson

Reputation: 13696

Both options have their drawbacks, as you suggest. A four argument constructor is hard to use correctly and makes the code hard to read. However, it communicates the intent that all parameters are mandatory.

A builder would be easier to use and make the code easier to read, but communicate the intent that the arguments are optional.

Since code is more often read than written, I recommend to use the option that promotes readability in this case. Go for a builder and make sure that all paramters are validated when the build() method is called to fail as fast as possible when using the builder incorrectly. Use javadoc to assist with communicating that all parameters are mandatory.

Upvotes: 4

Crazyjavahacking
Crazyjavahacking

Reputation: 9697

If you want to create an immutable object, you have to provide a constructor with all necessary fields.

You cannot set the state partially as later you would have to add some notion of "setters" which would by definition add mutability.

Builder pattern is really about partial object building.

Upvotes: 5

Related Questions