vendredi 21 juillet 2017

Pattern to avoid "if failed cleanup" repetition

I have some code that looks like this:

int myfunc()
{
     blah a;
     blah2 b;
     blah3 c;
     blah4 d;
     blah5 e;

     int iRes = DoSomething1(a, b, c);
     if (iRes > 0)
     {
         clean1(a, b, c);
         clean2(d, e);
         log_error();
         return 1;
     }

     iRes = DoSomething2(a, c, e);
     if (iRes > 0)
     {
         clean1(a, b, c);
         clean2(d, e);
         log_error();
         return 1;
     }

     ...

     iRes = DoSomething10(c, d, e);
     if (iRes > 0)
     {
         clean1(a, b, c);
         clean2(d, e);
         log_error();
         return 1;
     }

     clean1(a, b, c);
     clean2(d, e);
     return 0;
}

How, in C or C++, avoid the repetition of if (iRes > 0) { clean1(a, b, c); clean2(d, e); log_error(); return 1; } after each function calls?


Notes:

  • In the real code, these functions DoSomethingx() and cleanx() are API functions, not written by myself
  • I'd like to avoid having a second function clean() defined outside of myfunct() that would handle the cleanup + error
  • I thought about using preprocessor macro, but I doubt it's a good practice for such situations

Example:

This code is an example of such a situation: every 10 lines of code is in fact = 2 lines only for actually doing something + 8 lines of error testing and cleanup... Can we do nicer?

Aucun commentaire:

Enregistrer un commentaire