我应该避免使用 Java 标签语句吗? [英] Should I avoid using Java Label Statements?

查看:34
本文介绍了我应该避免使用 Java 标签语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个同事建议我重构我的代码以使用标签语句来控制流过我创建的 2 个嵌套 for 循环.我以前从未使用过它们,因为我个人认为它们会降低程序的可读性.但是,如果论点足够扎实,我愿意改变使用它们的想法.人们对标签声明有什么看法?

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?

推荐答案

如果您可以跳过两个循环(或包含 switch 语句的循环),则可以更轻松地表达许多算法.不要为此感到难过.另一方面,它可能表示一个过于复杂的解决方案.所以退后一步看问题.

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.

这篇关于我应该避免使用 Java 标签语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆