by wicknicks · 12y ago · 0 comments
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-option...
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.