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?

0

2 Answers 2

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.

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

6 Comments

that's exactly the same as if I placed it in the if statement. If this is considered the elegant approach, that's what I prefer :)
Yes and that is why I added my answer: other answers take a step too far.
I will edit my code kind sir ... thank you
Not "shortcut", but short circuit.
@Lauren_G don’t edit your question to become an answer. It’s confusing readers to have a “question” that says the same as the answer.
|
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.

4 Comments

what if the value is not a constant?
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.
@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).
The object != null test is obsolete at this place. It can’t be null at this point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.