The article is translated from winterbe.com/posts/2015/…
When it comes to Java programming, the NullPointerException null pointer is notorious. Do not say that primary programmers will encounter, even intermediate, expert programmers a little careless, will fall into this pit.
Tony Hoare, the creator of the Null reference, apologized in 2009, saying that nullpointer anomalies have cost businesses billions of dollars so far.
Here’s What Tony Hoare said:
I call the null-referenced design a multi-billion dollar mistake. In 1965, I was designing the first fully functional system in an object-oriented language (ALGOL W). My concern at the time was to make sure that all references used were safe and that the compiler would check automatically. However, I didn’t resist the temptation to add Null references, just to simplify the implementation. Since then, it has resulted in countless bugs, errors, and system crashes, as well as incalculable losses for the enterprise.
It is what it is, and we must learn to live with it. So, how do we prevent null-pointer exceptions?
The only way to do that is to add checks to objects that may be Null. But Null checking is tedious and painful. So newer languages have added special syntax to handle Null checks, such as the Null merge operator.
Also known as the Elvis operator in languages like Groovy or Kotlin.
Unfortunately, no such syntactic sugar is available in older versions of Java. This has been improved in Java8. So, this article is designed to show you how to write nullpointerexceptions in Java8 using new features.
★★★ If this tutorial is helpful to you, go to GitHub to help Star, thank you! Portal u u u
How to enforce Null object checking in Java8?
In the previous article, the Java8 feature guide briefly covered how to short check objects using the Optional class. Next, let’s talk more about it:
Nested objects within objects is a common scenario in business systems, as shown in the following example code:
// Outermost object
class Outer {
Nested nested;
Nested getNested(a) {
returnnested; }}// Layer 2 object
class Nested {
Inner inner;
Inner getInner(a) {
returninner; }}// The lowest level object
class Inner {
String foo;
String getFoo(a) {
returnfoo; }}Copy the code
In business, if we need to get Outer against foo in the underlying Inner, we have to write a bunch of non-null validations to prevent nullPointerExceptions:
// Tedious code
Outer outer = new Outer();
if(outer ! =null&& outer.nested ! =null&& outer.nested.inner ! =null) {
System.out.println(outer.nested.inner.foo);
}
Copy the code
Through the Optional
In Java8, we have a more elegant solution, which is Optional, which means we can do a flow-through map operation in one line of code. The map method is automatically null-checked internally:
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo
.ifPresent(System.out::println); // If it is not null, the value of foo is finally printed
Copy the code
Customize the enhanced API through the Suppiler function
The suppiler function is the ultimate solution to this problem:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
// A null pointer exception may be thrown, returning an empty Optional object
returnOptional.empty(); }}Copy the code
Use the resolve method above to refactor the above non-null validation code snippet:
Outer obj = new Outer();
// Call resolve directly, internally nulling pointer handling
resolve(() -> obj.getNested().getInner().getFoo());
.ifPresent(System.out::println); // If it is not null, the value of foo is finally printed
Copy the code
The last
What you need to know is that these two solutions are not as efficient as traditional NULL checking for performance. But in the vast majority of business scenarios, giving up a little bit of performance to make coding easier is perfectly acceptable, except in scenarios where performance is critical, and we don’t recommend it.
In my opinion, it is better to optimize SQL statements, business logic, etc.