Why LocalDate
, LocalTime
, Stream
, etc. objects use a factory method of()
instead of a constructor?
I found an exp
+1 to Peter's answer.
Another reason for using factory methods is that they act like "named constructors".
For example, LocalDate
has 6 static factory methods (at least, I may not be exhaustive here):
of(int year, int/Month month, int dayOfMonth)
(two overloads)ofEpochDay(long epochDay)
ofYearDay(int year, int dayOfYear)
parse(CharSequence text)
parse(CharSequence text, DateTimeFormatter formatter)
I think that it is a lot clearer to understand the meanings of the various parameters by having these as separately-named methods, rather than a bunch of constructors with very similar parameter types; you can pretty much guess what the parameters should be for the factory methods, whereas you might actually have to read the Javadoc (shock horror) if they were "unnamed" constructors.
Admittedly, of
is the least clear of these names - one might want ofYearMonthDayOfMonth
- however, I suspect that this is the most commonly-used factory method, and it's just too cluttered to type that long name all the time.
In case you've not read it, Item 1 of Effective Java 2nd Edition is all about why and when to prefer static factory methods over constructors. The "named constructor" advantage I mention here is actually the first advantage Bloch highlights.