How to properly handle if statements containing both null checks and non-null checks together in an OR expression

77 Views Asked by At

I have some code that does the following:

if(object == null || object.value.equals(" ")) {
    // do something
}
else {
   // do something else 
}

The above seems dangerous to me because if I switched the order of the two conditions or changed this to an AND expression, the code will crash when object is null, but I also read somewhere that Java guarantees operands are evaluated from left to right. That said, I also read do not assume this to be true.

I am confused by all this conflicting advice and wondering whether the above code constitutes a bug. That said, what is the best way to recode this if indeed this is considered bad practice?

2

There are 2 best solutions below

6
Joop Eggen On BEST ANSWER

In Java && and || are short circuit (boolean!) operators. So everything works as assumed. No unnecessary evaluation running into an error. Some languages Name these and-then, or-else.

boolean newGraphRequired = graphNode == null
    || gaphNode.timeStamp() != moduleNode.timeStamp();

Conditions become more straightforward.

4
AudioBubble On

Use below piece of code -

  if(object == null || (object != null && " ".equals(object.value))) {
        // do something
    }
    else {
        // do something else 
    }

Also Always keep constant values in left side of equals, it will prevent NPE.

For Above code if object is null or object.value is " "(space), it will go inside if otherwise it will go in else.