Reputation: 97
if (Functioncall){}
else if (Functioncall){}
if (Functioncall){}
if (Functioncall){}
if (Functioncall){
if (Functioncall){
if (Functioncall){}
}
}
else {}
Each function call returns a boolean value and depending on the return value, a set of statements are executed. I'm trying to get rid of the if-else ladders which seem to clutter up the code.
How can I do so?
Upvotes: 0
Views: 1988
Reputation: 31972
Depending on how your code is written, the nested if
s can be written as one big if
if(Function1 && Function2 && Function3){
}else{}
If your code was
if (Functioncall){
if (Functioncall){
if (Functioncall){
// the code
}
}
}
Then the above code is identical.
Upvotes: 2
Reputation: 35464
It looks like your functions are all returning a bool
. Does the return true
mean succeeded and false
mean failed? If so then you should change the the functions to be void
and throw an Exception
when they fail. Then the calling code does not need to check the return value.
Upvotes: 0
Reputation: 17508
You can check for the opposite conditions and return "early". That way, you will have much cleaner code flow, much less indents, and probably a bit clearer logic when you (or someone else) reads your code.
Have a look at these:
In your case, it would be something similar to:
if (!Functioncall)
return;
if (!OtherFunctioncall)
return;
etc.
Upvotes: 2
Reputation: 706
You have some options:
Upvotes: 1