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
- Is it advisable to keep adding the new fields to the already overloaded constructor?
- Create a new overloaded constructor every time I need to add a new field so that I don’t break dependent code?
- Or simply use the default empty default constructor and use setters only (messing up my immutability, which is not of high concern)
What is the advice that you can give me?
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.