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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With