Should I avoid using Java Label Statements?

前端 未结 11 1460
北荒
北荒 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 04:44

    I've never seen labels used "in the wild" in Java code. If you really want to break across nested loops, see if you can refactor your method so that an early return statement does what you want.

    Technically, I guess there's not much difference between an early return and a label. Practically, though, almost every Java developer has seen an early return and knows what it does. I'd guess many developers would at least be surprised by a label, and probably be confused.

    I was taught the single entry / single exit orthodoxy in school, but I've since come to appreciate early return statements and breaking out of loops as a way to simplify code and make it clearer.

提交回复
热议问题