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 variableversion
will be assigned to null ifcomputer
is null, orgetSoundcard()
returns null, orgetUSB()
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
Your post really cool and interesting. Thanks very much.
ReplyDeleteSamsung - 14" Geek Squad Certified Refurbished Laptop - 8GB Memory - 750GB Hard Drive
Samsung - Geek Squad Certified Refurbished 15.6" Laptop - 6GB Memory - 750GB Hard Drive