Java中Optional使用注意事项

栏目: Java · 发布时间: 6年前

内容简介:Java中Optional使用注意事项

Java中Optional使用注意事项

之前遇到过使用Optional之后带来的隐含bug,现在强调记录一下不好的用法,防止错用。

Optional不能序列化,不能作为类的字段(field)

这点尤为重要,即类要纯粹。如果是POJO就原始类型就可以了,如果是领域对象,则更不应该使用Optional作为field。

Optional不能作为方法参数

另一种不太适合使用Optional的情况是将该类型作为方法或者构造函数的参数,这将导致不必要的代码复杂化。

User user = new User("john@gmail.com", "1234", Optional.empty());

相反,使用方法重载(method overloading)来处理非强制性参数要方便得多。

Optional和steam组合更有益处

级联调用是危险的,很容易产生空指针。比如

String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();

在传统做法里,

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }
        }
    }
}

使用Optional可以精简代码,降低复杂度:

String result = Optional.ofNullable(user)
  .flatMap(User::getAddress)
  .flatMap(Address::getCountry)
  .map(Country::getIsocode)
  .orElse("default");

总结

Optional类对我们最有帮助的一个用例是同Stream或者其他方法组合使用,这些方法会返回一个可构建流畅API的Optional值。如果仅仅作为判空,那么不要使用Optional,直接判null就好。

比如,使用Stream 的Optional对象的例子:

@Test
public void whenGetStream_thenOk() {
    User user = new User("john@gmail.com", "1234");
    List<String> emails = Optional.ofNullable(user)
      .stream()
      .filter(u -> u.getEmail() != null && u.getEmail().contains("@"))
      .map( u -> u.getEmail())
      .collect(Collectors.toList());
   
    assertTrue(emails.size() == 1);
    assertEquals(emails.get(0), user.getEmail());
}

参考

原文链接: https://stackify.com/optional-java/

关于作者:

Eugen是一名软件工程师,对Spring、REST API、安全和教育拥有极大热情。同时,他还是Baeldung(推特账号@baeldung)的创始人。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning Google Maps API 3

Beginning Google Maps API 3

Gabriel Svennerberg / Apress / 2010-07-27 / $39.99

This book is about the next generation of the Google Maps API. It will provide the reader with the skills and knowledge necessary to incorporate Google Maps v3 on web pages in both desktop and mobile ......一起来看看 《Beginning Google Maps API 3》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具