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
You might look at the Builder pattern advocated by Joshua Bloch, and described in Effective Java. There’s a presentation with the main points at http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-2689.pdf; no doubt you could dig up a better reference.
Basically, you have another class, probably an inner class, which provides methods named after the properties being set, and which return the original builder so you can chain calls. It makes for quite a readable chunk of code.
For example, let’s suppose I have a simple
Messagewith a few properties. The client code constructing this could use a builder to prepare aMessageas follows:A fragment of
Message.Buildermight look similar to the following: