Deva
Deva

Reputation: 3949

java Nested If or single if

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();

Upvotes: 15

Views: 1008

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

As per my understanding the Option 1 will have extra overhead as it has to evaluate the same expression multiple times

Yes, these calls would be made multiple times. However, you can shorten it if you make assignments as part of your conditional, like this:

SoundCard sc;
USB usb;
if(computer != null && (sc = computer.getSoundCard()) != null && (usb = sc.getUSB()) != null) {
    version = usb.getVersion();
}

Note that references to sc and usb inside the expression and inside the conditional are safe, because && evaluation is guaranteed to stop upon reaching the first false in the chain.

Upvotes: 17

shihpeng
shihpeng

Reputation: 5381

A better approach is to extract this USB-version-getting code into another single method, say getComputerUsbVersion(), then flatten the super long if or the nested if-else block into several simple if blocks:

public String getComputerUsbVersion(Computer computer) {

    if (computer == null)  return null; 

    SoundCard soundCard = computer.getSoundCard();
    if (soundCard == null) return null; 

    USB usb = soundCard.getUSB()
    if (usb == null) return null;

    return usb.getVersion();
}

As you can see, the code is much cleaner and easy to understand, the super long if condition or the nested if-else block is also avoided. You can even add more condition checking code to this method later on very easily.

Upvotes: 24

Related Questions