3

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.

Adam Alyyan
  • 420
  • 5
  • 8
  • 2
    Do any of the parameters naturally fit together as part of something bigger? (For example, if you've got "FirstName, LastName, Address1, Address2, Address3" then that sounds like you've really for "Name" and "Address".) – Jon Skeet Feb 10 '15 at 07:19
  • If you always have these parameters defined at the time of object creation then I do not see a problem with a single constructor. – PM 77-1 Feb 10 '15 at 07:19
  • @JonSkeet The parameters are more or less as fine grain as they will go in this case, but you raise a good point if they were more related. – Adam Alyyan Feb 10 '15 at 07:22
  • Possible duplicate of [The builder pattern and a large number of mandatory parameters](http://stackoverflow.com/questions/7302891/the-builder-pattern-and-a-large-number-of-mandatory-parameters) – Roland Mar 17 '17 at 14:24

2 Answers2

5

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.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
4

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.

K Erlandsson
  • 13,408
  • 6
  • 51
  • 67