Thursday, 27 March 2014

Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!

Make your code more readable and protect it against null pointer exceptions.

A wise man once said you are not a real Java programmer until you've dealt with a null pointer exception. Joking aside, the null reference is the source of many problems because it is often used to denote the absence of a value. Java SE 8 introduces a new class called java.util.Optional that can alleviate some of these problems.

What's possibly problematic with the following code?
String version = computer.getSoundcard().getUSB().getVersion();

What can you do to prevent unintended null pointer exceptions? You can be defensive and add checks to prevent null dereferences.

String version = "UNKNOWN";
if(computer != null){
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null){
    USB usb = soundcard.getUSB();
    if(usb != null){
      version = usb.getVersion();

The above code will work without any issues, however it is not good to see and not readable.

We just wrote the above lines to check the null references..! is it good ?

Here is the Java 8 feature.

String version = computer?.getSoundcard()?.getUSB()?.getVersion();
In this case, the variable version will be assigned to null if computer is null, or getSoundcard() returns null, or getUSB() returns null. You don't need to write complex nested conditions to check for null.
which can be used for simple cases when a default value is needed. In the following, if the expression that uses the safe navigation operator returns null, the default value "UNKNOWN" is returned; otherwise, the available version tag is returned.
String version =  computer?.getSoundcard()?.getUSB()?.getVersion() ?: "UNKNOWN";

Thank you..!
Chandrasekhara Kota

Related Posts Plugin for WordPress, Blogger...