4 ms·
Hmm, if I understood that code it could be written like this: Session s; if ((s = request.getSession(false) != null) return ImmutableMap.of(....)
by mike_hearn 12y ago
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.
- matwood 12y agoShifting 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/UsingAndAvoidingNullExplained https://code.google.com/p/guava-libraries/wiki/UsingAndAvoid...