Wednesday, 21 February 2018

Java 9 - Avoid Null Pointer Exception with requireNonNullElse and requireNonNullElseGet methods

(Download One Minute Java Mobile app for latest Java updates 
App Link : One Minute Java )

Overview
Java 7 and Java 8 provided some better ways to handle null pointer exceptions by providing variants of requireNonNull().
But Java 9 came up with 2 methods requireNonNullElse() and requireNonNullElseGet() using which you can provide a default value and can avoid throwing Null Pointer exception.
All the variants of requireNonNull are static methods of java.util.Objects class.
Lets iterate over all these methods in below section.

Java 7 introduced requireNonNull()
requireNonNull method in Java 7 has 2 variants requireNonNull(T obj) and requireNonNull(T obj,String message).
lets have a look at example so that we can understand it better.

Example

  public void city(String latitude, String longitude) {

 this.latitude = Objects.requireNonNull(latitude);
 this.longitude = Objects.requireNonNull(longitude, "longitude must not be null");

 }


Output 1: when latitude is passed null

  Exception in thread "main" java.lang.NullPointerException
    at at java.util.Objects.requireNonNull(Unknown Source)


Output 2: when longitutde is passed null

 Exception in thread "main" java.lang.NullPointerException: longitude must not be null
    at at java.util.Objects.requireNonNull(Unknown Source)


Advantages
As we can see in output 2 a more redable customized message can be conveyed using this method.
requireNonNull also makes code more redable and less cluttered.

Java 8 addition
Java 8 added new variant requireNonNull(T obj,Supplier &ltString&gt messageSupplier).
This is the optimised version as it helps to defer the creation of message string till it is actually needed.
Creating a string at runtime is costly affair and you can avoid it using supplier, below is what Java doc says :
This method allows creation of the message to be deferred until after the null check is made. While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the message supplier are less than the cost of just creating the string message directly.

How to use Supplier

  String name = null;

 Objects.requireNonNull(name, new Supplier&ltString&gt() {
   @Override
   public String get() {
   return "Name cannot be null";
   }
 });


Java 9 addition
Java 9 further added 2 more methods requireNonNullElse​(T obj,T defaultObj) and requireNonNullElseGet​(T obj, Supplier&lt ? extends T&gt supplier).
These methods return first argument if it is non-null and otherwise returns the default non-null second argument.
Main advantage of this is, you can avoid throwing null pointer exeception.

Example

  Employee emp = null;

  Employee emp2 = Objects.requireNonNullElse(emp, new Employee());


Explaination
Since emp is null in above example another object of same type is returned, thus avoding NullPointerException.
Second variant of this method accepts a Supplier for returning a default value instead of new object of same type.
As discussed earlier Supplier has added advantage of differing execution until it is needed.


No comments:

Post a Comment