As far as I know Java SE 8
has java.util.Optional<T>
class that protects the code against unintended null
pointer exceptions. But for some reasons I have to use Java 7
.
Take a look at my example:
String version = device.getController().version;
What is the best practice to check device
and getController()
for null?
Option 1:
String version = "unknown";
if(device!=null){
if(device.getController()!=null)
version = device.getController().version;
}
Option 2:
String version = "unknown";
if(device!=null && device.getController()!=null){
version = device.getController().version;
}
Option 1 is a bit cumbersome, but obviously it will work correctly. The second options is questionable, because the fact that we do not know which part of condition will be checked first and how Java
actually do it. There is a point to suggest that Java
checks 2 parts of conditions before returning the result. Obviously, the second part will return NullPointerException
in case device is null. So, what is the best way to check nested objects in Java 7 and earlier?