Constructor with all class properties or default constructor with setters?

Alberto Zaccagni picture Alberto Zaccagni · May 6, 2009 · Viewed 7k times · Source

Following are the two approaches:

  • constructor with all the class properties

Pros: I have to put an exact number of types of parameters so if I make an error the compiler warns me (by the way, is there a way to prevent the problem of having erroneously switched two Integer on the parameter list?)

Cons: if I have lots of properties the instantiation line can become really long and it could span over two or more lines

  • setters and the default empty constructor

Pros: I can clearly see what I'm setting, so if I'm doing something wrong I can pinpoint it as soon as I'm typing it (I can't make the previuos error of switching two variables of the same type)

Cons: the instantiation of an object with lots of properties could take several lines (don't know if this is really a con) and if I forget to set a property the compiler doesn't say anything.

What will you do and why? Do you know of any light pattern (consider that it should be used everytime an object wth 7+ properties is instantiated) to suggest? I'm asking this because I tend to dislike large constructors where I can't figure out fast where is the variable I'm looking for, on the other hand I find the "set all properties" vulnerable to missing some of the properties.

Feel free to argument my assumptions in pros and cons as they are only mine thoughts :)

Update - a question I've found which is related to this: Building big, immutable objects without using constructors having long parameter lists

Answer

Jon Skeet picture Jon Skeet · May 6, 2009

You've missed the biggest pro of having a constructor with loads of parameters: it lets you create immutable types.

The normal way of creating immutable types without huge constructor nastiness is to have a helper type - a builder which maintains the values you'll want in your final object, then builds the immutable object when you're ready.