Many years ago, I posted a problem I had with some code and received a well written detailed answer that suggested the use of factory methods. I liked this approach, because I can provide a method name to let clients know what was being created, and to prevent wrong parameters.
// Left out additonal parameters and validation
private Student(StudentType type, List<String> documents) {
this.type = type;
this.documents = documents;
}
public static Student createDomestic() {
return new Student(StudentType.DOMESTIC), Collections.emptyList());
}
public static Student createInternational(List<Document> documents) {
return new Student(StudentType.INTERNATIONAL, new ArrayList<>(documents);
}
Benefits:
- I don't need a private method to validate the
List
based on theStudentType
, it made the code shorter and cleaner. All I needed was to check if theList
provided for theInternational
students contained documents (by checking the length of theList
). - The static factory prevents clients from assigning a
Domestic
student aList
of documents, which according to the requirements it shouldn't have.
Leaving aside the POLA, is using a static
factory method the way it was suggested on SO, considered a code smell or bad practice?