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:
Maybe I'm weird but I find the old fashioned version far easier to read than the new form.
[ Parent
| on HN ]
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...