Max
Max

Reputation: 97

How to get rid of if-else statement clutter?

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

Answers (4)

Karthik T
Karthik T

Reputation: 31972

Depending on how your code is written, the nested ifs 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

Richard Schneider
Richard Schneider

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

Ofer Zelig
Ofer Zelig

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

jelgh
jelgh

Reputation: 706

You have some options:

  • Switch-case-clauses
  • Make your code better modularized. Break out into methods (easier to see duplicated code aswell)
  • Check for opposite and return immediately. Might help you with nested ifs

Upvotes: 1

Related Questions