Re:Java 8 Features
by matwood on Friday May 30, 2014 @10:52AM
(#7822096)
I don't think @NotNull/@Nullable go away completely, but the use of optional makes dealing with nullables much easier. I think this is a much cleaner ways to deal with possible nulls:
If/When HttpServletRequest is updated to support Optional it can return it directly instead of the caller having to do it, and that is when Java will really see the upside.
[ Parent
| on HN ]
Re:Java 8 Features
by mike_hearn on Friday May 30, 2014 @12:07PM
(#7822519)
Hmm, if I understood that code it could be written like this:
Session s;
if ((s = request.getSession(false) != null)
return ImmutableMap.of(....);
else
throw new IllegalStateException();
Maybe I'm weird but I find the old fashioned version far easier to read than the new form.Shifting the null checking to the type system is the biggest win. So, assuming the getSession() returned an optional:
public ImmutableMap<String, Long> getSessionTime(HttpServletRequest request) {
return request.getSession(false)
.map(s -> ImmutableMap.of("lastAccessedTime", s.getLastAccessedTime()))
}
The above would not work because the call is returning another optional. The null is forced to be dealt with instead of allowing it to lead to programmer error[1]. The construct makes the programmer either call either orElse(), orElseGet(), or orElseThrow(). The programmer could also just return the optional and let the caller deal with it.Of course this is a trivial example where the programmer is likely expecting null, but many times null can be returned and it is not always clear.
[1] https://code.google.com/p/guava-libraries/wiki/UsingAndAvoid...