Java nested if statement versus if-else

I'm not sure which of the following code snippets I should prefer.

A) Nested

if(cond1 != null) {
    if(cond2 != null) {
        //Do the good stuff here
    } else {
        System.out.println("Sorry cond2 was null");
    }
} else {
    System.out.println("Sorry cond1 was null");
}

B) flat

if(cond1 == null) {
    System.out.println("Sorry cond1 was null");
} else if(cond2 == null) {
    System.out.println("Sorry cond2 was null");
} else {
    //Do the good stuff
}

I think B is more readable. But what is more like Java?

+7
source share
3 answers

The second option is if-then-elsemore readable and is used in the documentation https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html .

This may depend on your project code, but deep code embedding should be avoided since it is not readable. The representation of a surface nested statement is not welcomed ifinstead if-then-else.

, , , Objects.requireNonNull:

Objects.requireNonNull(cond1);
Objects.requireNonNull(cond2);
//Do the good stuff
+10
+6

B

, .

:

public String doWork(String arg1, String arg2)
{
    if(arg1 == null || arg2 == null)
    {
        // do stuff
        return null; // if you wish to...
    }

    // do important stuff
}

:

, /.

, , , , (, , ).

, , runtime, .

+1
source

All Articles