【问题标题】:"Optional value should only be accessed after calling isPresent()" although checked in if for multiple values“仅在调用 isPresent() 后才应访问可选值”,尽管检查了多个值
【发布时间】:2022-01-19 10:22:00
【问题描述】:

我收到一个包含姓氏和名字的客户对象。在转换中,我检查两个值是否不为空,然后将它们传递给 DTO:

if (customer.getFirstName().isPresent() && customer.getLastName().isPresent()) {
      final String firstName = customer.getFirstName().get();
      final String lastName = customer.getLastName().get();
      // do assignment
}

但我仍然收到 Sonar 消息 只能在调用 isPresent() 后访问可选值

我在这里遗漏了什么还是误报?

【问题讨论】:

  • 如果getFirstName 在您第二次调用它时返回不同的值怎么办?
  • 使用ifPresentget 违背了使用Optional 的目的。在这种情况下,空检查更容易阅读。
  • 好点。在这种情况下,不可能返回其他东西,但我明白了。
  • Optional 不应用作属性类型。请参阅stackoverflow.com/questions/23454952/uses-for-optional,它对此主题有权威的回答。
  • 如果我只是传递它,那么当我必须进行空值检查或稍后再次将其打包到 Optional 中时,将其解包并没有任何好处。但这与我上面的问题无关。谢谢。

标签: java sonarqube


【解决方案1】:

如何使用 ifPresent

customer.getFirstName().ifPresent(name1->
  customer.getLastName().ifPresent(name2->
      final String firstName = name1;
      final String lastName = name2;
  );
);

【讨论】:

  • 我喜欢这个解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多