Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple return statement in java [closed]

Tags:

java

private void test() {           
        // Nested if block 
        if (true) { // If condition is true
            if (true) { // If condition is true
                if (true) { // If condition is true
                    if (true) { // If condition is true
                         // statement
                    }
                }
            }
        }

        // Above block breaking in below way
        // Breaking nested if in multiple with return statement
        if (false) { // If condition is false
            return;
        }

        if (false) { // If condition is false
            return;
        }

        if (false) { // If condition is false
            return;
        }

        if (false) { // If condition is false
           return;
        }
    }

OOPs suggest multiple return statement is bad idea. But if I used multiple nested if then its look very complex. Please suggest what is best way to use nested if condition

like image 301
Shiladittya Chakraborty Avatar asked Dec 01 '17 11:12

Shiladittya Chakraborty


1 Answers

Multiple return statements is not good or bad in itself.
Early return and fail fast principle are not bad ways of coding and yet they rely on multiple return statements.
A single thing matters : the consistence and the code readability.

Your second way uses the "early return" pattern :

if (false) { // If condition is false
    return;
}

if (false) { // If condition is false
    return;
}

if (false) { // If condition is false
    return;
}

if (false) { // If condition is false
   return;
}

Now nothing prevents you from improving this code by removing the duplication : if (...) returns ...;.
Abusing of these can indeed finish to produce a less readable code because too noises and scattered rules.

Your example is really too abstract to provide a specific answer.
So, suppose that multiple of your conditional statements rely on a object of a specific class to be evaluated.

In this case, you could store conditional statements in a List and iterate on it to apply each rule. As soon as one is not valid, you exit.

List<Predicate<MyObject>> predicates = Arrays.asList(MyObject::isValid, 
                                                    (m)-> m.getColor()==BLUE);

And now apply rules :

MyObject myObj = ...;
for (Predicate<MyObject> predicate : predicates) {
    if (!predicate.test(myObj)) {
      return false;
    }
}
like image 103
davidxxx Avatar answered Oct 01 '22 07:10

davidxxx