我听说返回是不好的做法null。
在这种情况下,除了退货还有哪些选择null?
public RollingStock getHeadPoint() {
if (!train.isEmpty()) {
return train.get(0);
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
恕我直言,最好的选择是返回一个Optional<RollingStock>,如下所示:
public Optional<RollingStock> getHeadPoint() {
if (!train.isEmpty()) {
// or even Optional.ofNullable, if you are not sure
// whether train.get(0) is null or not
return Optional.of(train.get(0));
} else {
return Optional.empty();
}
}
Run Code Online (Sandbox Code Playgroud)
假设train是一个集合,作为手动将值包装到Optional您可以使用的替代方案Stream API:
public Optional<RollingStock> getHeadPoint() {
return train.stream()
.findFirst();
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,使用内联train.stream().findFirst()可能比将其包装到单独的方法中更可取。
一旦您修改了getHeadPoint返回方法Optional<RollingStock>,您就可以按如下方式使用它:
// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1701 次 |
| 最近记录: |