15

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();
7
  • 9
    Can you to use Java 8 on your project... If yes, look at this: docs.oracle.com/javase/8/docs/api/java/util/Optional.html Commented Sep 18, 2015 at 2:51
  • 1
    They are both good. I'd usually go with option 1 because it's more concise. Option 2 might be better if 1) you change to version = usb.getVersion(), and 2) any of the getter methods might be slow. Commented Sep 18, 2015 at 2:54
  • 1
    and... java compiler will to optimize that kind of tasks... try to look at generated jvm code for your code... it's more optimized than you thought. Commented Sep 18, 2015 at 2:54
  • 3
    Assuming these methods return reference to objects (or null) - the performance penalty for calling the same getter twice is negligible. That said, if you're performing heavy computation inside any of these methods - that's indeed something to consider. Commented Sep 18, 2015 at 2:57
  • 2
    @Deva Getter methods are usually just returning a field, so cost is nil. Usually. Commented Sep 18, 2015 at 3:07

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree because this form will encapsulate the logic to get the usb version. Well, the function name could be more specific, like findSoundCardUsbVersion... "find", not "get", because get presumes with it exists... and there are many points of return on the method.
Even better would be to raise an exception (and log an error) when null is found.
17

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.

1 Comment

Just to add: You should realize that you are defining those variables sc and usb in a much wider scope as you might need. I would not want to read an if expression like this in my source code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.