首页 > 技术文章 > 优雅的编码,使用Optional代替if-else

asachenjh 2021-08-13 17:08 原文

Optional是JAVA8引入的类,它其实是一个包装类,可以对所有对象进行包装, 包括null,这个特性使得我们编码可以优雅的解决空指针异常。

 

先编写一些测试类

    class Student {
        private ClassRoom classRoom;

        public ClassRoom getClassRoom() {
            return classRoom;
        }

        public void setClassRoom(ClassRoom classRoom) {
            this.classRoom = classRoom;
        }
    }

    class ClassRoom {
        private Seat seat;

        public Seat getSeat() {
            return seat;
        }

        public void setSeat(Seat seat) {
            this.seat = seat;
        }
    }

    class Seat {
        private Integer row;

        private Integer column;

        public Integer getRow() {
            return row;
        }

        public void setRow(Integer row) {
            this.row = row;
        }

        public Integer getColumn() {
            return column;
        }

        public void setColumn(Integer column) {
            this.column = column;
        }
    }

先来看看以前传统我们编码怎么避免空指针异常的

        Student student = new Student();
        if (student != null) {
            ClassRoom classRoom = student.getClassRoom();
            if (classRoom != null) {
                Seat seat = classRoom.getSeat();
                if (seat != null) {
                    Integer row = seat.getRow();
                    System.out.println(row);
                }
            }
        }  

如果使用Optional的代码

Student student = new Student();
        Integer row = Optional.ofNullable(student)
                .map(Student::getClassRoom)
                .map(ClassRoom::getSeat)
                .map(Seat::getRow)
                .orElse(null);
        System.out.println(row);

重点在于orElse方法

public T orElse(T other) {
        return value != null ? value : other;
    }

方法里面做了非空判断,我们就可以传入一个如果对象为空时候的默认值;

可以看出Optional的方法许多都返回Optional对象,所以它支持链式调用;

而且大多方法入参都是Supplier 函数式接口,因此支持java8的JAVA Lambda表达式。

推荐阅读