我的项目中有一个复杂的模型结构。
有时我必须得到一个deep从中放置价值。它看起来像下面这样:
something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
问题是每个方法都可能返回null
,我会得到NullPointerException
以防万一。
我想知道的是如果喜欢我应该写长吗
if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
//process getFourthSomething result.
}
或者只使用 try..catch 就可以了,如下所示:
SomethingFourth fourth = null;
try {
fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }
if(fourth != null) {
///work with fourth
}
我知道NPE
是一件应该避免的事情,但就我而言,避免它不是开销吗?
如果可以重构代码,让每个方法都返回Optional
。可以避免空检查并尝试...捕获。
Optional<Result> result = something.getSomethingElse()
.flatMap(e -> e.getSecondSomething())
.flatMap(x -> x.getThirdSomething())
.flatMap(e -> e.getFourthSomething());
// at the end to check if result is present
result.ifPresent(..some_logic_here..); // or result.orElse(...);
so getSomethingElse()
回报Optional<SomethingElse>
, getThirdSomething()
- Optional<ThirdSomething>
等等。我们必须在这里使用flatMap(Function<? super T,Optional<U>> mapper)
因为如果提供的映射器的结果已经是可选的,并且如果被调用,则 flatMap 不会用附加的可选来包装它。换句话说,如果map
on map(e -> e.getSecondSomething())
结果类型将是Optional<Optional<SecondSomething>>
我们将不得不做不必要的事情get()
call - map(...).get().map(...)
.
我希望这有帮助。
UPDATED您可以使用方法引用执行相同的操作。
Optional<Result> result = something.getSomethongElse()
.flatMap(SomethongElse::getSecondSomething)
.flatMap(SecondSomething::getThirdSomething)
.flatMap(ThirdSomething::getFourthSomething);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)