Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring away labeled loops

After I was convinced that labeled breaks/continues are a total "nono" over here, I need help to remove the label out of my code.

I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.

I hope, the code-fragment is basically understandable…

vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
    if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;

    matrixLoop:
    for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
        if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
        if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
    }
    setValueInVector( v, idx );
}     

Please convince me, that there is a more readable/better version without the labels.

like image 871
Mo. Avatar asked Aug 19 '08 07:08

Mo.


2 Answers

Looking at the solutions presented so far:

  • They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself

  • Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.

  • Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.

  • Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed.

All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn't need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule.

like image 157
Marcus Downing Avatar answered Oct 20 '22 13:10

Marcus Downing


@Patrick you are assuming calling setValueInVector( v, idx ); at the end of the second loop is OK. If the code is to be identical, logically, it must be rewritten to somethng like this:

for( int idx = 0; idx 
like image 1
Anders Sandvig Avatar answered Oct 20 '22 14:10

Anders Sandvig