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.
You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will. The only way to guarantee initialising the fields is to assign them.
Default Constructor – A constructor that accepts no parameter is called Default Constructor. It is not necessary to have a constructor block in your class definition. If you don't explicitly write a constructor, the compiler automatically inserts one for you.
Constructors can also take parameters, which is used to initialize attributes.
The constructors are used to initialize the instance variable of a class or, create objects. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class.
If after you create an object you have to call set
or init
to 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.
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:
MyShape(Point c1, Point c2,...., Point c10, Color c, Name n)
As you can see, I've omitted the connected shape because it can sensibly be set to NULL
if 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:
MyShape(Point c1, Point c2,...., Point c10, Color c, Name n,
MyShape* connectedShape /*=NULL*/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With