Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "if" chains?

Assuming I have this pseudo-code:

bool conditionA = executeStepA(); if (conditionA){     bool conditionB = executeStepB();     if (conditionB){         bool conditionC = executeStepC();         if (conditionC){             ...         }     } }  executeThisFunctionInAnyCase(); 

Functions executeStepX should be executed if and only if the previous succeed. In any case, the executeThisFunctionInAnyCase function should be called at the end. I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if chain producing that sort of "pyramid of code", at the expense of the code legibility?

I know that if we could skip the executeThisFunctionInAnyCase function call, the code could be simplified as:

bool conditionA = executeStepA(); if (!conditionA) return; bool conditionB = executeStepB(); if (!conditionB) return; bool conditionC = executeStepC(); if (!conditionC) return; 

But the constraint is the executeThisFunctionInAnyCase function call. Could the break statement be used in some way?

like image 456
ABCplus Avatar asked Jun 26 '14 12:06

ABCplus


People also ask

Should I avoid nested if statements?

Always prevent yourself from writing nested if-else statements. By keeping this to mind, we will be more effective in writing good, testable codes, and we will be a more productive member of the team we are in.


1 Answers

You can use an && (logic AND):

if (executeStepA() && executeStepB() && executeStepC()){     ... } executeThisFunctionInAnyCase(); 

this will satisfy both of your requirements:

  • executeStep<X>() should evaluate only if the previous one succeeded (this is called short circuit evaluation)
  • executeThisFunctionInAnyCase() will be executed in any case
like image 194
Shoe Avatar answered Oct 12 '22 11:10

Shoe