【发布时间】:2021-08-19 16:49:26
【问题描述】:
是否可以使用 Optional 重写以下内容?在我看来,当情况需要抛出异常时,使用 Optional 可能不是一个好主意?
Item item = service.get(id);
if (item == null) {
throw new ItemNotFoundException();
}
item.setValue(false);
itemDao.update(item);
尝试 1:
Optional.ofNullable(service.get(id))
.ifPresent(item -> {
item.setValue(false);
itemDao.update(item);
}); // cannot throw exception inside the consumer
尝试 2:
Optional.ofNullable(service.get(id))
.map(item -> {
item.setValue(false);
itemDao.update(item);
})
.orElseThrow(new ItemNotFoundException()); //can throw exception here but the usage of map is not correct
【问题讨论】:
-
首先,
Optional应该被该方法用作返回类型。如果可能,将service.get更改为返回Optional。 -
不要试图把每一个空检查都变成使用
Optional的东西。如果检查 null 的语句未被弃用。 -
你必须写
orElseThrow(ItemNotFoundException::new)。 IE。您创建一个可以按需创建异常的供应商。 -
理想情况下,您首先让该方法返回
Optional。如果那不可行,我会坚持使用常规的 if-else。除非您想自己返回 Optional。
标签: java