I have two options. Either make a class that accepts a lot arguments in its constructors, or create a lot of setter methods and an init method. I’m not sure which is preferred option, should some arguments be accepted in constructors, while others could be manually set via setter? Or am I over-thinking this?
This is a relevant question, also by me: Conflicts between member names and constructor argument names.
If after you create an object you have to call
setorinitto actually use it… well, that’s just an awful design.If the object is usable without some of the members initialized the way you want them to be, you can set them later on.
The golden rule here is – if you create an object, you should be able to use it without doing any other sort of initialization.
Expanding on the answer:
Say you have a shape with 10 sides, 10 corners, a color and a name, that can be connected to a different shape. The constructor should look like:
As you can see, I’ve omitted the connected shape because it can sensibly be set to
NULLif the current object is not connected. However, in the absence of any of the other parameters, the object isn’t valid, so they should be set in the constructor.A possible overload (alternitively a default argument) can be: