简体   繁体   中英

Checking if an Object is null at the same time as a value of one of it's fields

Which of these would be correct?

if(dialog != null && dialog.isShowing){}

if(dialog.isShowing && dialog != null){}

if(dialog != null){
   if(dialog.isShowing){}
}

The first and third ones are both OK to use because they won't process past the null check. The second one can result in a NullPointerException because it's referencing dialog before you've checked if it's null.

The && operator in Java will stop evaluating (from left to right) as soon as it encounters a false. Therefore in

if(dialog != null && dialog.isShowing){}

dialog.isShowing() will not be called if the dialog is null and is therefore "safe" to use.

This:

if(dialog != null){
   if(dialog.isShowing){}
}

will work as well, but generally nesting if-statements like this is avoided as it decreases readability.

Even though everything has been answered, for the sake of completeness: The way Java evaluates conditional clauses is called Short circuit evaluation . This means that once the result of the condition is asserted, further clauses will not be evaluated.

Edit: My statement is not completely true actually. Java uses Short circuit evaluation when using || and && (which is the standard what every programmer uses, thus my statement in the first place), but you may force Java to evaluate all statements by using & and |

The && operator is called a short circuit operator. This means once the result is known. ie, false && x is always false it doesn't evaluate the remaining expressions.

A variation on this is using the || short circuit, OR operation, like:

if(text == null || text.isEmpty())

It's shortcut logic. When first expression is false, Java will not check second expression, because whole expression is false definity.

  • First case is best practice.
  • Second case is incorrect.

You may use try and catch if you want to use the second one otherwise the first and the third one are correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM