0

I'm having trouble with shortening multiple guarded clauses with cleanup causing hundreds of lines for condition checks and repetition of code. This is making me sick of scrolling. How do you deal with this kind of problem?

For example,

if (conditionA)
{
    return errorA;
}

B* pB = allocateB();
if (pB->Initialize() != S_OK)
{
    // Cleanup
    freeB();
    return errorB0;
}

if (conditionB)
{
    // Cleanup
    freeB();
    return errorB1;
}

C* pC = allocateC();
if (conditionC)
{
    // Cleanup
    freeC();
    freeB();
    return errorC;
}

DoSomethingWithC(pC);
... so on

Example is quite simplified so it might not seem dirty, but real world situation functions have more than 6 parameters, indexing, arrows, etc. sum up mess.

I can't write as below

if (conditionA) freeB(); return errorB;

or using logical operators

if (!conditionA &&
    allocateB()->Initialize() == S_OK &&
    ...)

because former violates coding standard and latter I can't have error codes.

Reason for guard clause

Reason for braces after if statement 1, 2, 3 (Misra 2012 Rule 15.6)

When this logic involves thread safety and mutex locks, each if statements get longer exit routine.

I found using GOTO for this kind of situation. However, goto is not accepted not only in coding analysis tools or rules, but also not accepted in general.

Perhaps replacing each condition with macro will help? undefing after usage? Or is use of RAII the best option?

YoonSeok OH
  • 647
  • 2
  • 7
  • 15

0 Answers0