Hate Russian dolls? Use Java 8's Optional<T> class and functional programming syntax!

Table of contents

1. Problems and solutions

2. Understand the principle of implementation

1. First knowledge of Java functional programming

2. Usage of Optional


1. Problems and solutions

Java programmers should be very familiar with the if non-empty judgment of this kind of nesting doll:

    public String getCourse(Student stu) throws Exception {//该方法根据学生获取其课程
        if(stu != null){ // 这里必须写非空判断
            Teacher t = stu.getTeacher();//获取学生的老师
            if(t != null){ // 这里必须写非空判断
                return t.getCourse();//返回老师的课程
            }
        }
        return "无课程";
    }

See, in order to obtain the value of the course attribute of the Teacher attribute of the Student object, and to avoid NPE (the abbreviation of NullPointerException), it has to be written so verbosely. But if you don't write it like this, your code will report NPE every minute. Fortunately, Java 8 provides a new syntax to change this situation, first look at the effect:

    public String getCourse(Student stu) throws Exception {

        return Optional.ofNullable(stu)
                .map(s -> s.getTeacher())
                .map(t -> t.getCourse())
                .orElse("无课程");
    }

This is to use the Optional<T> class provided by Java 8 to simplify the code for conditions such as non-empty . In addition, this also uses the syntax of Java 8 functional programming, so chain calls can be realized, and the code is smooth and readable . Mom no longer has to worry about me writing a lot of if nesting dolls!

 

2. Understand the principle of implementation

1. First knowledge of Java functional programming

The java.util.Optional<T> class is used above, let’s take a look at the main methods of the Optional<T> class:

The parameters of Consumer, Function, and Supplier types in the above method are all functional programming interfaces provided by Java 8. You can first understand that achievements are code fragments. In other words, starting from Java 8, the parameters of a method can be not only primitive types, objects, but also a code fragment (technical name is 'lambda expression'). For example, when traversing a List collection based on Java 8, a syntax prompt will pop up in IDEA:

The parameter in the brackets of forEach is a Consumer<...> type. Written into code is:

List<Student> stuList= new ArrayList<>();
stuList.forEach(s -> System.out.println(s)); //括号中的 s -> System.out.println(s)就是一个代码片段(表达式)

The s -> System.out.println(s)  in the parentheses of the above code is a code fragment (expression). See, the code fragment can be passed as a parameter.

Well, about the grammatical features of functional programming, stop here, and if you are interested, go to the relevant information, and get down to business.

2. Usage of Optional<T>

The role of the Optional class is to wrap a layer of shell for the object you want to operate. With it, if you need to do different things in the code according to whether the object is null or not, it will be more convenient and more convenient. Elegantly avoid NPE exceptions.

Do you still remember the if nesting doll code at the beginning of this article? Change it to Optional to implement it, and you can write it like this (lower first for easy understanding):

    public static String getCourse(Student stu) throws Exception {
        //把要操作的stu包装到Optional对象中,即使stu是null也不会抛空指针异常
        Optional<Student> stuOpt = Optional.ofNullable(stu);
        //用map方法把s(是stu的别名)对象的teacher属性拿出来,也包装到Optional中,
        Optional<Teacher> teaOpt = stuOpt.map(s -> s.getTeacher());
        //用map方法把Teacher对象的course属性拿出来,也包装到Optional对象中,
        Optional<String> courseOpt = teaOpt.map(t -> t.getCourse());
        //返回courseOpt中course属性的值,如果为null就返回“无课程”
        return courseOpt.orElse("无课程");

    }

If you feel that this code is too much, then we use chain calls to simplify it, and see the final writing method:

    public String getCourse(Student stu) throws Exception {

        return Optional.ofNullable(stu)
                .map(s -> s.getTeacher())
                .map(t -> t.getCourse())
                .orElse("无课程");
    }

Follow me, a man who has written code for more than ten years and has not been bald.

Guess you like

Origin blog.csdn.net/liudun_cool/article/details/116521317