Reputation: 2594
I often structure my code like this:
public void doSomething() {
if (!condition1) {
println("problem 1");
return;
}
if (!condition2) {
println("problem 2");
return;
}
if (!condition3) {
println("problem 3");
return;
}
// code to run if
// everything is OK
}
rather than nesting like this:
public void doSomething() {
if (condition1) {
if (condition2) {
if (condition3) {
// code to run if
// everything is OK
}
else {
println("problem 3");
}
}
else {
println("problem 2");
}
}
else {
println("problem 1");
}
}
Is there any benefit to one over the other? Is one more "correct" than the other? Thanks!
Upvotes: 0
Views: 3250
Reputation: 411
You should profile your code, see which condition is true most of the times. If there is a significant discrepancy in the number of times each condition is true, then by all means use the first structure, arranging your code to take advantage of your domain-specific input. This may gain you some significant performance benefit.
Upvotes: 1
Reputation: 2594
Either code structure is fine, but having multiple return
statements adds another layer of complication when debugging, and can be more prone to errors when typing and/or editing code.
Upvotes: 0
Reputation: 18702
if(condition1){
} else if(condition2){
} else if(condition3){
} else {
}
or use switch statements. There's no significant performance benefit here. Use the one that is more readable/suitable in your situation. One more thing I should add is that in some cases switch statements are faster as with if..else you will have checking of different clauses until it reaches the one matches or there's no match at all.
Upvotes: 0
Reputation: 608
whenever i see multiple if's, i think of moving to switch
statements, for more readability..and avoid multiple repeated ....if words....
Upvotes: 0