In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use Optional to get rid of the torture of NPE. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
In my current work, I have used a lot of Stream and Lambda expressions in Java, and I have written two previous articles to summarize the corresponding knowledge.
024:Java streams implement Shell:cat 1.log | grep a | sort | uniq-c | sort-rn
Functional programming makes you forget design patterns
However, the feature of Optional has not been well used, so recently I began to read the book "Java 8 practice", in which this article is a summary of Chapter 10.
Background
In Java, if you try to make a function call to null, it will throw NullPointerException (NPE). NPE is the most typical exception in Java program development. For Java developers, whether you are a newcomer or a veteran driver for many years, NPE often turns them over. To avoid NPE, they add a lot of if judgment statements, making the code less readable.
From the perspective of software design, null itself is a meaningless semantics, which is a wrong modeling of missing variables.
From the perspective of the Java type system, null can be assigned to any type of variable and passed on until in the end no one knows where it was introduced.
The introduction of Optional
Java designers took inspiration from Haskell and Scala and introduced a new class java.util.Optional in Java 8. If an interface returns Optional, it can indicate that a person may or may not have a car, which is clearer than simply returning Car, and the person who reads the code does not need to prepare business knowledge in advance.
This is the purpose of Optional: to make the knowledge hidden in your domain model explicitly reflected in your code through the type system.
The usage of Optional describes how empty returns an empty Optional instance filter. If the value exists and the provided filter condition is met, the Optional object containing the value is returned. Otherwise, an empty Optional object map is returned. If the value exists, the provided mapping function call flatMap is executed on the value. If the value exists, the provided mapping function call is performed on the value, returning a value of type Optional. Otherwise, an empty Optional object ifPresent is returned. If the value exists, the method call using the value is executed, otherwise nothing is done. Of will specify the value and return it with Optional, if the value is null. Throw a NPEofNullable to encapsulate the specified value in Optional and return it. If the value is null, an empty Optional object orElse is returned if there is a value, otherwise a default value orElseGet is returned if there is a value, otherwise a value generated by the specified Supplier interface is returned (if the default value is expensive to generate, it is appropriate to use the orElseGet method) orElseThrow returns if there is a value Otherwise, an exception get thrown by the specified Supplier interface is returned. If the value exists, the value is returned. Otherwise, a NoSuchElementException exception isPresent is thrown. If the value exists, true is returned, otherwise false is returned.
The basic API of Optional is listed in the above table, and I list some of the tips used here:
You can use ofNullable to encapsulate a possible null object as an Optional object, and then use the orElse method to provide the default value; you can use the empty method to create an empty Optional object; the of method is generally not used, but if you know that a value cannot be null, you can use Optional to encapsulate the value, so that once it is null, it will throw an exception.
/ / use of the empty method Optional optCar = Optional.empty ()
/ / use of the of method
Optional optCar = Optional.of (car)
/ / use of the ofNullable method
Optional optCar = Optional.ofNullable (car)
-you can use the map method to retrieve the value of a field in the value it encapsulates in the Optional object; ````JavaOptional optInsurance = Optional.ofNullable (insurance); Optional name = optInsurance.map (Insurance::getName)
If you need to continuously and progressively get the value of a field from the end of an object chain, you can't all use the map method. You need to use flatMap first, and then use the map method at last.
/ / public String getCarInsuranceName (Person person) {return person.getCar () .getInsurance () .getName ();} before conversion
/ / after conversion
Public String getCarInsuranceName (Optional person) {
Return person.flatMap (Person::getCar)
.flatMap (Car::Insurance)
.map (Insurance::getName)
.orElse ("Unknown")
}
The map, flatMap and filter methods in Optional are similar in concept to the corresponding methods in Stream, except that there is at most one element in Optional, which is a special case of Stream-a special collection. -do not use ifPresent and get methods, which are essentially the same pattern as before they are not applicable to Optional objects, and are bloated if-then-else judgment statements -because Optional cannot be serialized, it is impossible to define a field as Optional in the domain model because Optional is only designed to support syntax that returns Optional objects. If we want to introduce Optional into the domain model, we can use the following alternative method: ```Javapublic class Person {private Car car; public Optional getCarAsOptional () {return Optional.ofNullable (car);}}
Do not use Optional objects of the base type because Optional objects of the base type do not support map, flatMap, and filter methods, which are very powerful methods in Optional.
Practical case case 1: using tool-like methods to improve API that may throw exceptions
The Java method handles exception results in two ways: return null (or error code), and throw an exception, such as Integer.parseInt (String). If the corresponding integer cannot be resolved, the method throws a NumberFormationException. In this case, we usually use the try/ catch statement to handle the exception.
In general, we recommend that you extract the try/catch block into a separate method, which is designed here using Optional, as shown in the following code. In development, you can try to build an OptionalUtility utility class that encapsulates these complex try/catch logic.
Public static Optional stringToInt (String a) {try {return Optional.of (Integer.parseInt (s));} catch (NumberFormationException e) {return Optional.empty ();}} case 2: comprehensive case
Now there is a way to try to get the corresponding value of a keyword from an attribute mapping. The example code is as follows:
Public static int readDuration (Properties properties, String name) {String value = properties.getProperty (name); if (value! = null) {try {int I = Integer.parseInt (value); if (I > 0) {return I }} catch (NumberFormatException e) {}} return 0;}
After using the Optional method, the code is as follows:
Public static int readDurationWithOptional (Properties properties, String name) {return Optional.ofNullable (properties.getProperty (name)) .flatMap (OptionalUtility::stringToInt) .filter (integer-> integer > 0) .orElse (0);}
If the property value you need to access does not exist, the return value of the Properites.getProperty (String) method is a null, which can be converted to an Optional object using the noNullable factory method; next, you can use flatMap to convert an Optional to an Optional object; finally, you use filter to filter out negative numbers, and then you can use orElse to get the property value, and if you can't get it, return the default value of 0.
Thank you for reading! This is the end of this article on "how to use Optional to get rid of the torture of NPE". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.