58 lines
4.8 KiB
Markdown
58 lines
4.8 KiB
Markdown
---
|
||
title: "Java: Because I eliminated all the “if (object == null)” in the project, my boss rewarded me with…"
|
||
source: "https://levelup.gitconnected.com/java-because-i-eliminated-all-the-if-object-null-in-the-project-my-boss-rewarded-me-with-29b316c32329"
|
||
author:
|
||
- "[[Dylan Smith]]"
|
||
published: 2024-08-23
|
||
created: 2024-10-29
|
||
description: "In this article, I will introduce how to combine lambda expressions with Optional to make Java judge whether an object is null more elegantly."
|
||
tags:
|
||
- "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 let’s introduce it in detail.
|
||
|
||
In the previous article we have introduced [Lambda expression in java](https://medium.com/@junfeng0828/lambda-expression-in-java-439268b0ab97). In this article, I will introduce how to combine Lambda expression and Optional make Java handle null more gracefully.
|
||
|
||
Suppose we have a student object,and 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 Lambda,such 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!
|
||
|
||
Let’s now compare the following four common null handling differences between Java8’s 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. |