简体   繁体   中英

Avoid nested if for null and parameter condition

Is it possible to avoid nested if statements while I want to check if variable/object is null and if variable/object meet some condition eg.

var obj = "test";
if (obj != null) {
   if (obj.equals("test")) {
      //do something;
   }
}

Is it possible to do oneliner of this statement without defining own method which handle this ?

You can also try (in Java)

"test".equals(obj)

this way, you don't have to do an explicit null check,

You could make use of the null-conditional operator ? and the null-coalescing operator ?? :

if(obj?.Equals("test") ?? false)
{
   // do something
}

Where obj?.Equals("test") returns null if obj is null and ?? assigns false to the if-statement if the value befor ?? is null .

But sadly this will only work in C#, not in Java. Java only knows the conditional operator ? but not the null-coalescing operator ?? ( is there a Java equivalent to null coalescing operator (??) in C#? ).

I suggest you to get familiar with short-circuit of conditional statements

If you will call your conditions with && as following:

if (obj != null && obj.Equals("test"))
{
    //do something;
}

You will not get an exception, because if obj == null it will return false on the first parameter and will not check the second parameter of && statement.

The same logic is implemented in || - if first argument is true another arguments will not be checked.

Short-circuiting is also implemented in java , so you can implement nested if s as the sequence of && operators both in c# and java .

Use Logical && instead for nesting if . The && will evaluate the second condition only when the first one is true(the same thing that the nested if doing). So obj.equals("test") will be evaluated only when the first condition is true ie., obj!=null

if(obj!=null && obj.equals("test"))
{
   // do something;
}

Yes, you can.

But check for null should be first , then if your object is null it would break:

var obj = "test";
if(obj != null && obj.equals("test")){
    // do something;
}

operator && can permit you to do that.

if(obj!=null && obj.equals("test")){
    //do something
}

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