【问题标题】:Using consumer and throw exception in Optional在 Optional 中使用消费者并抛出异常
【发布时间】: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


【解决方案1】:

正如之前的答案中提到的 - 服务方法应该返回一个可选的。 如果您绝对想使用 Optional 和未更改的服务方法,请执行以下操作:

Item item = Optional.ofNullable(service.get(id)).orElseThrow(ItemNotFoundException::new);

item.setValue(false);
itemDao.update(item);

【讨论】:

    【解决方案2】:

    你应该在地图上归还物品。

    Optional.ofNullable(service.get(id))
    .map(item -> {
       item.setValue(false);
       itemDao.update(item);
       return item;
    }).orElseThrow(ItemNotFoundException::new);
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 2016-06-10
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多