Should I avoid using Java Label Statements?

前端 未结 11 1457
北荒
北荒 2020-11-29 04:27

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 per

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 05:04

    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.

提交回复
热议问题