用 Optional#ifPresent 替换 null 检查的好处

Benefit of replacing null-checks with Optional#ifPresent

我刚刚从 Java 7 移动到 8,我的代码中到处都是像

这样的片段
if (myObj != null) {
    myObj.doSomething();
    myObj.doOtherThing();
}

我注意到空检查有时被认为是一种反模式,Java8 提倡使用 Optional。让我的代码看起来像

有什么好处吗
Optional.ofNullable(myObj).ifPresent(obj -> {
    myObj.doSomething();
    myObj.doOtherThing();
});

可以说,它使代码更难阅读。

Optional 的优点之一是,当您从方法中 return 一个 Optional 时,它表明该方法可以 return null。当 returning 一个普通对象时,是否应该对 returned 值进行空检查并不明显。