2

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?

Holger
  • 285,553
  • 42
  • 434
  • 765
Lauren_G
  • 55
  • 6

2 Answers2

2

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

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.

  • what if the value is not a constant? – Lauren_G Jan 10 '23 at 04:51
  • If value is not constant then you will have to add one more null check as - object != null && null != object.value && object.value.equals("other non constant value"). Also I am not talking about object.value to be constant, its the other one like space in your case. –  Jan 10 '23 at 05:04
  • @Lauren_G The reason to do `" ".equals(object.value)` is because `" "` is a "constant", and is guaranteed to not be `null`. The `String#equals(Object)` method will return `false` if the argument is `null` (it won't throw an NPE). – Slaw Jan 10 '23 at 05:10
  • 1
    The `object != null` test is obsolete at this place. It can’t be `null` at this point. – Holger Jan 10 '23 at 09:08