In the new date package in Java 8, we changed from using "new Date()" to "LocalDate.of()".
Date d = new Date(year, month, dayOfMonth); //Old way
LocalDate d2 = LocalDate.of(year, month, dayOfMonth); //new way
When you want a new object you usually use the new
keyword. This is an intuitive way to create a new object.
Sometimes, when you need a singleton with delayed initialization you can use a static method to get the instance. In this case you must call it getInstance()
so developers know what to expect.
This new syntax makes the code less intuitive. It forces you to learn how to deal with specific objects instead of simply using them.
Are there any good reasons under the hood for this change?
java.time
has a section named Design notes (non normative), which says theof
prefix is used for "static factory methods" as part of the hope of making the API more manageable. – Doggeryof
replacednew
. There's also factory methods such asLocalDate#ofInstant(Instant,ZoneId)
,LocalDate#ofYearDay(int,int)
,LocalTime#ofNanoOfDay(long)
,LocalTime#ofSecondOfDay(long)
,LocalDateTime#ofEpochSecond(long,int,ZoneOffset)
and so on. Reading those method names is much clearer than each class having 5+ constructors and having to determine which constructor is being used, and what it does, by tediously inspecting the arguments. – DoggeryDatatypeFactory.newInstance()
(since Java 1.5).Integer.valueOf()
.IntStream.of()
. – Fondanew
is intuitive for guaranteeing a new instance, whileof
is intuitive for not caring whether you get a new instance or an existing one. And sinceLocalDate
and friends are immutable and value-based, you do not care. – Fonda