There are a few topics similar to this, but I couldn't find one with a sufficient answer.
I would like to know what is the best practice for constructor overloading in Java. I already have my own thoughts on the subject, but I'd like to hear more advice.
I'm referring to both constructor overloading in a simple class and constructor overloading while inheriting an already overloaded class (meaning the base class has overloaded constructors).
Thanks 🙂
Best Answer
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
Make a parameter class
The constructor in Simple only either needs to split the
SimpleParams
parameter:…or make
SimpleParams
an attribute:Make a factory class
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
The constructor is then done in the same manner as with the parameter class:
Make a combination of both
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the
Simple
class that they're used the same way.