5 ms·
Re Optional<T>: If I get this right, the source code of the signature of many (many!) methods will now be twice the size of before, unless the names of your ty
by terranstyler 12y ago
Re Optional<T>:
If I get this right, the source code of the signature of many (many!) methods will now be twice the size of before, unless the names of your types and variables were already considerably bigger than "Optional<...>" (10 chars).
I hope it's worth this cost.
- wicknicks 12y agoYeah, I hope I am interpreting this the wrong the way. But instead of doing X.getA().getB().getC().getD() we have to X.flatMap(X::getA) .flatMap(X::getB) .map(X::getC) .orElse("UNKNOWN"); //[1] Not sure why this is going to be better? [1] http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html http://www.oracle.com/technetwork/articles/java/java8-option...
- necubi 12y agoThat's not a fair comparison, as the flatMaps are eating nulls (really Optional.empty()s) while the naked calls will throw NPEs. The equivalent code for the first case is: String result = "UNKNOWN"; T a = X.getA(); if (a != null) { T b = a.getB(); if (b != null) { String c = b.getC(); if (c != null) { result = c; } } } Optional (like Scala's Option or Haskell's Maybe) are useful because they force you to reason about "empty" cases. Whereas in typical java code there is no way for the compiler to force to you handle the possibility of nulls (thus leading to NPEs), Wrapping a type in Optional forces you to deal with the case where the result is not present, leading to more correct programs. Plus, it gives you handy tools for dealing with non-present values, like allowing a chain of computation--any step of which may fail--without needing failure checks on every step.