Files
second-brain/Clippings/Java Because I eliminated all the “if (object == null)” in the project, my boss rewarded me with….md

4.8 KiB
Raw Permalink Blame History

title, source, author, published, created, description, tags
title source author published created description tags
Java: Because I eliminated all the “if (object == null)” in the project, my boss rewarded me with… https://levelup.gitconnected.com/java-because-i-eliminated-all-the-if-object-null-in-the-project-my-boss-rewarded-me-with-29b316c32329
Dylan Smith
2024-08-23 2024-10-29 In this article, I will introduce how to combine lambda expressions with Optional to make Java judge whether an object is null more elegantly.
clippings

Recently, a friend of mine joined a new company. Since there was a lot of code in the project that directly judged whether an object is null. So my friend optimized it by using Optional and was praised by the boss.

Now lets introduce it in detail.

In the previous article we have introduced Lambda expression in java. In this article, I will introduce how to combine Lambda expression and Optional make Java handle null more gracefully.

Suppose we have a student objectand an Optional wrapper for the student object:

public class OptionalTest {    public static void main(String[] args) {        Student student = new Student("Bob", 18);        Optional<Student> studentOpt = Optional.ofNullable(student);    }    @Getter    @AllArgsConstructor    public static class Student {        private String name;        private Integer age;    }}

Optional cannot make the original cumbersome null check simpler if it is not used in conjunction with Lambdasuch as

if (student == null) {  return UNKNOWN_STUDENT;} else {  return student;}if (!studentOpt.isPresent()) {  return UNKNOWN_STUDENT;} else {  return studentOpt.get();}

Only when Optional is used in combination with Lambda can its true power be exerted!

Lets now compare the following four common null handling differences between Java8s Lambda + Optional and traditional Java.

Situation 1 — Start if it exists

if (student != null) {  System.out.println(student);}studentOpt.ifPresent(System.out::println);

Case 2 — Return if it exists, if not return fart or throw exception

if (student == null) {  return UNKNOWN_STUDENT;   } else {  return student;}return studentOpt.orElse(UNKNOWN_STUDENT);return studentOpt.orElseThrow(RuntimeException::new);

Case 3 — If it exists, it is returned. If not, it is generated by the function

if (student == null) {  return UNKNOWN_STUDENT;} else {  return generateWithFunction();}return studentOpt.orElseGet(() -> generateWithFunction());

Case 4 — Continuous null checks

public class OptionalCase {    public static void main(String[] args) {        Student student = new Student("Bob", 18,                new Street("Main Street", new City("Los Angeles", new State("CA"))));        System.out.println(getStateFromJava7(student));        System.out.println(getStateFromJava8(student));    }    private static String getStateFromJava7(Student student) {                if (student != null) {            Street street = student.getAddress();            if (street != null) {                City city = street.getCity();                if (city != null) {                    State state = city.getState();                    if (state != null) {                        String stateName = state.getName();                        if (stateName != null) {                            return stateName;                        }                        return "unknown";                    }                    return "unknown";                }                return "unknown";            }            return "unknown";        }        return "unknown";    }    private static String getStateFromJava8(Student student) {        Optional<Student> studentOpt = Optional.ofNullable(student);                return studentOpt                .map(Student::getAddress)                .map(Street::getCity)                .map(City::getState)                .map(State::getName)                .orElse("unknown");    }    @Getter    @AllArgsConstructor    static class Student {        private String name;        private Integer age;        private Street address;    }    @Getter    @AllArgsConstructor    static class Street {        private String name;        private City city;    }    @Getter    @AllArgsConstructor    static class City {        private String name;        private State state;    }    @Getter    @AllArgsConstructor    static class State {        private String name;    }}

It can be clearly seen from the above four situations that Optional + Lambda allows us to write a lot less ifElse blocks. Especially for situation 4, the traditional Java writing method seems lengthy and difficult to understand, while Optional+Lambda is refreshing, clear and concise.