When initialising a class, is it good practice to use the getter and setter functions in the constructors?
Or is it good practice to set the variables directly, since the constructor could be considered a kind of mutator?
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. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in a sub-class which is not initialised yet.
Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.
If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.
It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
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