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?
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.
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 caseIf 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