mercredi 28 mars 2018

Java nested if-statment vs 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 Java-like?

Aucun commentaire:

Enregistrer un commentaire