I am not sure if a similar question has been asked before, searched for it, but did not get any helpful answers.
As the question suggests, what is better, having an overloaded constructor or having multiple setter functions?
Scenario:
public class Something {
private int a;
private int b;
public Something(int a, int b) {
this.a = a;
this.b = b;
}
... // Do Something
}
Now, my basic requirement was for to have two parameters only. Now tomorrow, the requirement is changed and I am asked to add a new parameter, c and then the next day d, and given a statement saying we can have more fields.
I already have dependency for this constructor in multiple projects. Now, back to my question
What is the advice that you can give me?
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.
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.
In other words, constructor overloading in Java is a technique that enables a single class to have more than one constructor that varies by the list of arguments passed. Each overloaded constructor is used to perform different task in the class.
The job of a constructor is to put a newly created object into a valid initial state before that object is used. The job of a setter method is to change the state of an object.
The most pleasant way to do this is to continue adding the fields to your constructor -- having setters means you can't have immutable objects, and immutable objects are always nice -- but possibly to investigate the builder pattern, which can help you limit yourself to just one constructor that gets called and "filled in" by the builder object.
The good thing about a constructor, as opposed to setters, is that it allows you to enforce the setting of required properties for an instance, rather than having the object be in a bad state until its correct setters are called. Also, as the other posters mentioned, immutability can be a very good thing, particularly in a multi-threaded context.
Nevertheless, your instincts are correct: constructors can grow unwieldy. To second the other posters yet again, the builder pattern can give you the best of both worlds in this situation. If you don't want the builder to be a nested class of the product, as it is depicted in the Java example in the Wikipedia article, then just put it in the same package as the product, and give the product package-protected setters. Also, you can add logic to enforce the setting of mandatory properties when the caller declares building to be complete.
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