What does java8’s Optional feature do? Speaking of which, what advantage does it have over the old null judgment?

It can actually be viewed as a container that may or may not have a non-null value. The biggest benefit is that the code is semantically politically correct. It doesn’t matter if the code works, the politics have to be right.

  

For example, we have a FooList list class of type Integer that has two methods, one that returns the length of the list, and one that returns the largest value that is smaller than the FooList argument passed in.

In the absence of Optional, the code is as follows

  


The semantic problem is that the size method always returns a number, whereas maxNumberBelow does not. If the list is empty, size returns 0, and maxNumberBelow(100) returns what?

At this time everyone across the sea eight immortals, each show his powers.

1 Returns null. A more commonly used method.

2 returns an invalid value. The indexOf method in String, for example, returns -1.

3 Throw an exception. Such as EntityNotFoundException in JPA.

By the way, I think throwing exceptions is the least desirable form. First of all, without discussing whether it should be checked exceptions, throwing exceptions without records in the database does not seem to meet the definition of exceptions. It’s normal to have no data in the database. How can it be an anomaly? It’s not politically correct.

After the developer crossed the sea, users were dumbfounded. Why is that? Because no matter how they cross the sea, methods are semantically hard to tell which avatar the developer is using — method signatures don’t effectively indicate whether it returns a reasonable value every time, or how it behaves when it doesn’t. What is the manifestation of not being able to return a reasonable value? Return null? Return a special value, okay? Or throw an exception? When calling a method in the IDE, you can’t see it, you can only see the documentation!!

Let developers document well? It doesn’t exist!

Get developers to look at the documentation? It doesn’t exist!

Why is it that the Integer returned by size can be used arbitrarily, while the Integer returned by maxNumberBelow must be compared with a weird value? Racism?

Let developers sort this out? It doesn’t exist!

So please use Optional to solve all the above problems.

  


First, the return value makes it clear whether a method returns a reasonable value every time or a conditional return a reasonable value.

Second, the IDE can check that the Optional object is bypassing isPresent and calling get directly.

So here we have politically correct code.