I just had a discussion about parameterized constructors with my exercise instructor. He said it is bad practice having two or more constructors, especially parameterized constructors. Instead of constructors I should use only one empty constructor and for initialisation the factory method pattern.
So this is the first time, I've ever heard something like this. I did some research, but I could not find anything related. The only bad practices I've found are:
So my question is, what is best practice? Is it fine to set instance variables inside constructor or should I follow the advice and use the factory method pattern?
Whether you use a factory method or multiple constructors is really just personal preference, especially with Java 8 where you can easily use a constructor reference as a factory (That's all a constructor really is - a factory for making instances of the object). It's perfectly fine to have multiple constructors for a class, and if you have too many constructors in a class, that's a sign of a class that is doing too much, not that you need to switch to a factory. Constructors very much should be parameterized when a class requires specific input to be valid and null
/ 0
is not a sane default value.
What you should avoid, however, is allowing an object to exist in an invalid state. For example, consider the following class and factory:
public class MyList {
private Object[] backingArray;
public void setBackingArray(Object[] backingArray) {
this.backingArray = backingArray;
}
}
public class MyListFactory() {
MyList newMyList(int initialSize) {
MyList list = new MyList();
list.setBackingArray(new Object[initialSize]);
return list;
}
MyList newMyList() {
MyList list = new MyList();
list.setBackingArray(new Object[defaultSize]);
return list;
}
}
This is an example of bad design because I can ignore the factory and call new MyList()
directly and the object is essentially invalid until I also call setBackingArray()
. When using a factory pattern, you have to be very careful to make sure that other code can't create the object directly without going through the factory. (The above classes are also bad for a host of other reasons, but they're not relevant to the point I'm trying to make).