javaspecificationsoperands

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


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?


Solution

  • 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.