I have a basic doubt regarding the execution of the following code block (Sample):
String version = computer.getSoundcard().getUSB().getVersion();
Which might throw NullPointerException if Soundcard isn't there.
So I have ,
Option 1 :
if(computer!=null &&
computer.getSoundCard() !=null &&
computer.getSoundCard().getUSB()!=null) {
version = computer.getSoundcard().getUSB().getVersion();
}
Option 2 :
if(computer !=null){
SoundCard sc = computer.getSoundCard();
if(sc!=null){
USB usb = sc.getUSB();
if(usb!=null){
version = usb.getVersion();
}
}
}
As per my understanding the Option 1 will have extra overhead as it has to evaluate the same expression multiple times like computer.getSoundCard() 3 times, computer.getSoundCard().getUSB() 2 times.
Is my understanding correct ?
EDIT 1: Changed Option 2 from
version = computer.getSoundcard().getUSB().getVersion();
version = usb.getVersion(), and 2) any of the getter methods might be slow.