Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I’ve never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people’s opinions on label statements?
Advertisement
Answer
Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don’t feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
Some people prefer a “single entry, single exit” approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.