Elegant way of code - how does Java judge empty?

1 Introduction

In the actual project, we will have many places that need to judge the null check. If the null check is not performed, a NullPointerException may occur.

We mentioned the handling of exceptions in the previous article:

Let’s take a look at some empty judgment methods in actual projects

Usually we judge whether an object is Null, we can use Objects.nonNull(obj) in java.util, ObjectUtil in hutool or directly null != obj

2. Empty judgment of List

In a special project like List, it may not only be judged to be non-empty. For List, not equal to null and List.size() not equal to 0 are two different things. There are also interns in the company who often confuse these two. If list is not equal to null, it means that it has been initialized, and there is a piece of heap memory that belongs to it. Site, and a size of 0 means that nothing has been put into it. For example, if it is not equal to null, it means that I have a bottle now, and a size greater than 0 means that I have filled the bottle with water.

In actual projects, it is also found that list.isEmpty() is used to judge directly. Let’s take a look at the source code:

It is equivalent to judging whether there is water in the bottle (the premise is that the bottle already exists, if the bottle does not exist, a NullPointerException will be thrown).

So usually use list != null && list.size > 0 to judge, or directly use isEmpty of the CollUtil tool in HuTool. There are also Set, Map, etc.

3. String's null judgment

The concept of bottle and water is still used here. When String is null, calling equals(String) or length() will throw java.lang.NullPointerException.

There are several methods for judging empty strings:

1. One of the methods used by most people, intuitive and convenient, but inefficient:

if(a == null || a.equals(""));

2. Compare the string length, efficient:

if(a == null || a.length() == 0);

3. Java SE 6.0 has just begun to be provided, and the efficiency is similar to method 2:

if(a == null || a.isEmpty());

Of course, you can also use the org.apache.commons.lang.StringUtils tool.

StringUtils.isNotBlank(a);

* StringUtils.isNotBlank(null) = false

* StringUtils.isNotBlank("") = false

* StringUtils.isNotBlank(" ") = false

* StringUtils.isNotBlank("bob") = true

* StringUtils.isNotBlank(" bob ") = true

There is also an isNotEmpty() method in the tool class, and the difference between the two can be clearly seen from the comments

StringUtils.isNotEmpty(a);

* StringUtils.isNotEmpty(null) = false

* StringUtils.isNotEmpty("") = false

* StringUtils.isNotEmpty(" ") = true

* StringUtils.isNotEmpty("bob") = true

* StringUtils.isNotEmpty(" bob ") = true

4、Optional

The appearance of Optional is used to prevent NullpointException. Common methods are:

  • .empty(): Create an empty Optional instance
  • .of(T t) : Create an Optional instance, and report an exception for null
  • .ofNullable(T t): If t is not null, create an Optional instance, otherwise create an empty instance
  • isPresent() : Determine whether there is a value in the container
  • ifPresent(Consume lambda): If the container is not empty, execute the Lambda expression in parentheses
  • orElse(T t) : Get the element in the container, if the container is empty, return the default value in parentheses
  • orElseGet(Supplier s): If the calling object contains a value, return the value, otherwise return the value obtained by s
  • orElseThrow() : If it is empty, throw the defined exception, if it is not empty, return the current object
  • map(Function f): If there is a value to process it, and return the processed Optional, otherwise return Optional.empty()
  • flatMap(Function mapper): Similar to map, the return value must be Optional
  • T get() : Get the element in the container, if the container is empty, a NoSuchElement exception will be thrown

Let's look at a common example:

There are Boolean attributes in the baseInfo class. It returns false if it is empty, and takes its value if it is not empty. Four lines are required.

When using Optional, it can be done in one line, which is very elegant.

4.1 Creation of Optional objects

public final class Optional<T> {
    private static final Optional<?> EMPTY = new Optional<>();
    private final T value;
    //可以看到两个构造方格都是private 私有的
    //说明 没办法在外面new出来Optional对象
    private Optional() {
        this.value = null;
    }
    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }
    //这个静态方法大致 是创建出一个包装值为空的一个对象因为没有任何参数赋值
    public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }
    //这个静态方法大致 是创建出一个包装值非空的一个对象 因为做了赋值
    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }
    //这个静态方法大致是 如果参数value为空,则创建空对象,如果不为空,则创建有参对象
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }
}
复制代码

4.2 Usage scenarios

Scenario 1: Query an object in the service layer, judge whether it is empty after returning and process it

Scenario 2: Use Optional and functional programming, get it done in one line

5. Summary

The existence of each method must have applicable scenarios. In some cases, this kind of chain programming, although the code is elegant. However, the logic is not so obvious, and the readability has been reduced. You can use it according to the situation in your project.

Guess you like

Origin blog.csdn.net/wdj_yyds/article/details/130511593