Is it a bad form to use a while loop that will always run once in order to use break statements?

As an example:

function()
{
    calculation1();

    while(1)
    {
        if (test1() == FAIL) { break; }

        calculation2();

        if (test2() == FAIL) { break; }

        calculation3();

        if (test3() == FAIL) { break; }

        calculation4();

        break;
    }

    final_calculation();

    return;
}

      

Each test depends on the results obtained from all calculations before it. However, if the test fails, the rest of the calculations should be skipped.

An alternative approach would be to use a series of nested if () statements:

function()
{
    calculation1();

    if (test1() == SUCCESS)
    {
        calculation2();

        if (test2() == SUCCESS)
        {
            calculation3();

            if (test3() == SUCCESS)
            {
                    calculation4();
            }
        }
    }

    final_calculation();

    return;
}

      

However, this latter approach is starting to look terribly messy in all but a very abstract example like the one above. I believe the previous approach has improved significantly to longer, more complex code. Are there any reasons not to go with the first method?

+3


source to share


3 answers


I have no problem with this technique and use it often.

However, I usually format it like:



    bool success = false;  // Pessimistically assume we will fail
    do
    {
        calculation1();
        if (test1() == FAIL)
        {
            break;
        }

        calculation2();
        if (test2() == FAIL)
        {
            break;
        }

        calculation3();
        if (test3() == FAIL)
        {
            break;
        }

        calculation4();
        success = true;  // Note the success!
    } while(false);

    // TODO: Check the success-variable to know if we failed early, or went all the way through.
    final_calculation();

    return;
}

      

(Sometimes my colleagues don't like the conditional loop while(false)

)

+5


source


Ato is a transition. You should just use it and not hide it with a while loop.

And yes, this is considered harmful, but in this case there is no real way to avoid it without much more refactoring of the code.



This is a real issue and may not be worth fixing.

+3


source


Alternative

failed = false

if (!failed) {
   calculation1();
   if (test1() != SUCCESS)
      failed = true;
}
 if (!failed) {
   calculation2();
   if (test2() != SUCCESS)
      failed = true;
}
if (!failed) {
   calculation3();
   if (test3() != SUCCESS)
      failed = true;
}
if (!failed) {
   calculation4();
  }

      

final_calculation ();

(! failed to check the first one just for symmetry)

+1


source







All Articles