Correct posture using the optional mechanism in Java 8

preface

The functional programming features brought by Java 8 still have some obstacles for programmers who are used to imperative programming. We can only use them freely if we deeply understand all aspects of these mechanisms. Null processing is another headache other than try catch in Java programming. It requires a lot of non empty judgment template code, and the nesting level of program logic is too deep. In particular, the use of sets requires layers of empty judgment.

First, let's look at the structure diagram of the optional class:

If we don't explore it a little, we just understate that it can gracefully solve the problem of nullpointexception, so the code starts to write like this

Well, we have to say that our thinking is still in place. We just instinctively think that it is just a package of user instances, which is different from what we wrote before

There is virtually no difference This is the correct posture for using java 8 optional type

During the Rio Olympics, the news repeatedly mentioned that there was a problem with the five-star red flag, but I couldn't see what the problem was. Later, it was said that the posture of the little star worshipping the center was wrong Therefore, we should never take things we are used to for granted, and we won't feel anything wrong at all. In other words, when we switch to Java 8 optional, we can't inherit the thinking of null in the past. We should master the correct posture of new and correct use of Java 8 optional

Frankly speaking, when we are still using optional in the following ways, we have to start examining ourselves

Ispresent() and obj= There is no difference, our life is still startling step by step The get () call without ispresent () will receive an alarm in IntelliJ idea

Using the optional type as a property or method parameter is strongly not recommended in IntelliJ idea

Therefore, in optional, we should really rely on other methods besides ispresent() and get():

I sort out the above methods with a little confidence according to their approximate frequency of use

First, I have to mention three construction methods of optional: optional of(obj), Optional. Ofnullable (obj) and explicit optional empty()

Optional. Of (obj): it requires that the incoming obj cannot be null, otherwise it will fall on the NullPointerException exception before entering the role

Optional. Ofnullable (obj): it constructs an optional instance in an intelligent and tolerant way If you don't refuse, you can get optional Empty(), call optional if it is not null of(obj) .

Is that all we have to do is use optional Ofnullable (obj) once and for all, just construct an optional instance in the way of invariance and two variables? Not necessarily, otherwise optional Of (obj) why is it so exposed? Private can?

My own opinion is: 1 When we are very, very clear, we will pass it to optional When the obj parameter of of (obj) cannot be null, for example, it is an object newly created (optional. Of (new user (...))), Or a non null constant; 2. When we want to assert that obj is not null, that is, we want to immediately report nullpointexception exception and modify it immediately in case obj is null, instead of hiding null pointer exception, we should resolutely use optional Of (obj) to construct the optional instance without allowing any unpredictable null value to be hidden in the optional

Let's start how to use an existing instance of optional. Suppose we have an instance of optional < user > user. Here are some common examples. If (user. Ispresent()) {...} should be avoided else { ... } Several methods of application

Returns if it exists, and provides a default value if it does not exist

Existence is returned, and none is generated by the function

Existence does something to it

Map function grand debut

When user If ispresent() is true, get its associated orders. If it is false, return an empty set. If the orelse and orelseget methods above are weak, it is the responsibility of the map function. We can do this line

Map can be cascaded infinitely, for example, one more layer to obtain the uppercase form of the user name

This needs to be put before. The expansion of each level of call needs to put a judgment of null value

In this regard, groovy provides a secure property / method access operator

Swift has a similar syntax, which only works on optional types

Using ispresent () to handle NullPointerException is not elegant. It is elegant with orelse, orelseget, etc., especially the map method

For the others, filter () changes the unqualified value to empty (), flatmap () is always paired with the map () method, orelsethrow () returns directly when there is a value, and throws the desired exception when there is no value

One sentence summary: try not to call option directly when using option Get() method, optional Ispresent () should be regarded as a private method and should rely on other methods such as optional orElse() ,Optional. orElseGet(), Optional. Map () and other methods

Finally, the best way to understand java 8 option is to look at its source code util. Optional, only after reading the source code can you really have the most confidence in explaining. The optional methods basically call ispresent() internally to judge, process values when true, and do nothing when false

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>