博客
关于我
利用JDK8提供的Optional简化if else
阅读量:570 次
发布时间:2019-03-11

本文共 2103 字,大约阅读时间需要 7 分钟。

如何减少if else(条件判断)代码的冗长性?在软件开发中,条件判断是避免空指针异常的一种常见做法,但繁多的if else会让代码显得臃肿。Java 8提供的Optional类为我们提供了一种更简洁的解决方案。

1. Optional的基本使用

Optional类是一个可以包含或不包含值的容器,并专门用于处理可能 null 的值。其核心方法包括:

  • ofNullable(Object obj):如果obj为null,则返回一个不包含值的Optional;否则返回包含该值的Optional。
  • map(Function Tony):如果Optional包含值,执行Tony函数,返回一个新的Optional;若值为null,则返回一个不包含值的Optional。
  • orElseGet(Supplier supplier):如果Optional包含值,返回其值;若值为null,则运行supplier函数返回一个值。

2. 示例一:时间字符串转换

假设selectStartTime()从数据库中查询LocalDateTime值,则getStartTime()方法原本需要五行代码:

private String getStartTime() {    LocalDateTime dateTime = selectStartTime();    if (dateTime == null) {        return "2020-01-01 00:00:00";    }    return dateTimeToString(dateTime);}
private String getStartTime() {    return Optional.ofNullable(selectStartTime())        .map(dateTime -> dateTimeToString(dateTime))        .orElseGet(() -> "2020-01-01 00:00:00");}

3. 示例二:用户查询优化

原代码:

User user = getCacheUser(1);if (user == null) {    user = selectUserById(1);}

简化代码:

User user = Optional.ofNullable(getCacheUser(1))    .orElseGet(() -> selectUserById(1));

4. 示例三:多层条件判断

此前需要多层条件判断:

public String getCity(User user) throws Exception {    if (user != null) {        if (user.getAddress() != null) {            Address address = user.getAddress();            if (address.getCity() != null) {                return address.getCity();            }        }    }    throw new Exception("对象为空");}

简化后:

public String getCity(User user) throws Exception {    return Optional.ofNullable(user)        .map(u -> u.getAddress())        .map(a -> a.getCity())        .orElseThrow(() -> new Exception("对象为空"));}

5. 示例四:深入条件判断

简化多层条件判断:

public User getUser(User user) {    if (user != null) {        String name = user.getName();        if ("zhangsan".equals(name)) {            return user;        }    } else {        user = new User("zhangsan");        return user;    }}

简化后:

public User getUser(User user) {    return Optional.ofNullable(user)        .filter(u -> "zhangsan".equals(u.getName()))        .orElseGet(() -> new User("zhangsan"));}

通过使用Optional的链式方法,我们减少了冗长的条件判断,使代码变得简洁明了。这种方式不仅提高了可读性,还更安全地处理了可能的null值情况。

转载地址:http://amnvz.baihongyu.com/

你可能感兴趣的文章
python中什么是实例方法_在Python中创建实例方法对象的不同方法
查看>>
Python中使用cutecharts实现简单的手绘风格的图表
查看>>
python中使用dxfgrabber,解析dxf文件信息生成obj文件
查看>>
Python中使用ncmbot玩转网易云音乐
查看>>
Python中使用PIL快速实现二值图
查看>>
Python中使用PIL快速实现灰度图
查看>>
Python中使用pip install ncmbot时各种错误解决办法
查看>>
Python中使用requests和parsel爬取喜马拉雅电台音频
查看>>
Python中使用turtle绘制多个同心圆
查看>>
Python中使用turtle绘制棋盘详解
查看>>
Python中使用wordcloud生成漂亮的中文词云
查看>>
Python中使用wxpy定时机器人给微信好友发送每日一文
查看>>
Python中使用zip()并行迭代
查看>>
Python中使用推导式创建序列
查看>>
Python中信号处理程序和atexit处理程序的调用
查看>>
Python中关于txt的简单读写模式与操作
查看>>
Python中关于类和函数的初体验之"__init__"和"__str__"不是"_init_"和"_str_"
查看>>
python中函数接受参数为*args, **kwargs怎么办
查看>>
Python中切片的高效迭代
查看>>
python中列表乘法、eval、lambda、hasattr、assert、*(星)等的用法
查看>>