在 Java 中使用“return”来中断 for 循环是一种糟糕的风格吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4805258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it bad style to use 'return' to break a for loop in Java?
提问by Lemony
I'm doing a project with basic Java for a CS class. The project has a for loop nested inside a while loop.
我正在为 CS 类做一个带有基本 Java 的项目。该项目有一个嵌套在 while 循环中的 for 循环。
I am not allowedto use break
as a way of ending a for loop early. I found out that return
seems to have the same effect as break
. Is it bad style to use return
as a way to break the loop?
我不允许使用break
早结束for循环的方式。我发现这return
似乎与break
. return
用作打破循环的方式是不好的风格吗?
My for loop has to check through three different statements but if it finds one that is true then it is supposed to end straight away without continuing to check the rest of the statements.
我的 for 循环必须检查三个不同的语句,但如果它找到一个是真的,那么它应该立即结束而不继续检查其余的语句。
I tried to put a boolean operator in the while loop that controls the for loop but that doesn't control what goes on inside the for loop until the for loop gets to the end.
我试图在 while 循环中放置一个布尔运算符来控制 for 循环,但它不控制 for 循环内部发生的事情,直到 for 循环结束。
Also does it matter if return
doesn't return anything?
如果return
不返回任何东西也有关系吗?
299/01/11 Update: Thanks everyone so much for your comments. I found it really helpful to read through all the debates.
299/01/11 更新:非常感谢大家的评论。我发现通读所有的辩论真的很有帮助。
I spoke to my tutor and it turns out for the purposes of getting full marks, I shouldn't use return
either.
我和我的导师谈过,结果是为了获得满分,我不应该使用return
任何一个。
So I found the advice about setting a boolean in the 'for' loop really helpful, as I didn't know you could do that.
因此,我发现有关在“for”循环中设置布尔值的建议非常有用,因为我不知道您可以这样做。
回答by paxdiablo
They'll only be equivalent if the first thing after breaking out of the loop is a return
statement.
只有当跳出循环后的第一件事是一个return
语句时,它们才是等价的。
In any case, if your lecturer doesn't allow break
, they probably won't allow return
either.
无论如何,如果你的讲师不允许break
,他们可能也不会允许return
。
You should be aware that these rules have a good basis behind them (to prevent spaghetti code and make it easier to write maintainable code) but sometimes they're enforced over-zealously.
您应该意识到这些规则背后有很好的基础(以防止意大利面条式代码并使编写可维护的代码更容易),但有时它们会被过度执行。
For example, there's nothingunreadable about the segment:
例如,该段没有任何不可读之处:
if (x == 0)
return 0;
return x - 1;
even though it has multiple return
statements.
即使它有多个return
语句。
The supposedly preferred solution to the no-multiple-return crowd is something like:
所谓的无多重回报人群的首选解决方案是这样的:
int y = x - 1;
if (x == 0)
y = 0;
return y;
which is, in my opinion, both less readable and a waste of space.
在我看来,这既不可读又浪费空间。
The real problems occur when you have very complex logic and the hoops that people jump through to avoid break
and/or return
leads to conditionals that are darn-near unreadable.
当您拥有非常复杂的逻辑以及人们为了避免break
和/或return
导致几乎不可读的条件而跳过的圈套时,就会出现真正的问题。
Listen to your lecturer - they are, after all, the ones in control of what grade you get. Then, once you get into the real world, you can switch from dogmatism to pragmatism and make up your own mind.
听听你的讲师——毕竟,他们是控制你成绩的人。然后,一旦你进入现实世界,你就可以从教条主义转向实用主义,并做出自己的决定。
See herefor some good advice regarding these issues outside of educational institutions.
有关教育机构之外的这些问题的一些好的建议,请参见此处。
回答by Nikita Rybak
First of all, it's nota bad style to use break
, if you use it judiciously.
Although I understand why your professor insists on coding without break
for now (because so many people, especially beginners, tend to 'overuse' it), there's no reason to ban it completely.
首先,如果您明智地使用它,那么使用它并不是一种糟糕的风格break
。
虽然我理解为什么你的教授break
现在坚持不编码(因为很多人,尤其是初学者,倾向于“过度使用”它),但没有理由完全禁止它。
Is it bad style to use return as a way to break the loop?
Personally, I think you'll be fine: code will get only simpler. But obviously your professor is the higher authority here. The whole question is very subjective, thus I can't tell for him.
使用 return 作为打破循环的方式是不是很糟糕?
就我个人而言,我认为你会没事的:代码只会变得更简单。但显然你的教授是这里的更高权威。整个问题很主观,所以我不能告诉他。
But again, regardless of what your professor sais, using return
in a loop is nota bad style.
但同样,不管你的教授怎么说,return
在循环中使用并不是一种糟糕的风格。
回答by Simeon
This question seems to enter the territory of a very old still unresolved argument, the "Single vs. Multiple method exit points".
这个问题似乎进入了一个非常古老的仍未解决的争论的领域,即“单方法与多方法退出点”。
So if using return in a loop is worrying you (or your teacher), you (or he) could have a look here.
因此,如果在循环中使用 return 使您(或您的老师)担心,您(或他)可以看看这里。
To answer your question. In my (and not only my) opinion using a return in a loop is definitely OK.
回答你的问题。在我(不仅是我)看来,在循环中使用 return 绝对没问题。
Do note however that overusing it might decrease code readability (see linked answer for details/examples).
但是请注意,过度使用它可能会降低代码可读性(有关详细信息/示例,请参阅链接答案)。
回答by Sean Patrick Floyd
Also does it matter if 'return' doesn't return anything?
如果“返回”不返回任何内容也有关系吗?
That depends on your method's return type. if the return type is void, a return clause must be empty:
这取决于您的方法的返回类型。如果返回类型为 void,则返回子句必须为空:
return;
otherwise, a return clause must return the required type, e.g.
否则,return 子句必须返回所需的类型,例如
return true; // legal for boolean return type
return null; // legal for all object types
return "Hello"; // legal if return type is String
回答by Damian Leszczyński - Vash
This is about perfect code.
这是关于完美的代码。
for(int i; i < stop; i++) {
boolean flag = true;
while(flag && condition) {
//some action
if(shouldIstop) {
flag = false;
}
}
}
When you set the flag to false then you will exit from the while, when you will set i to stop then you also will exit from for.
当您将标志设置为 false 时,您将从 while 退出,当您将 i 设置为 stop 时,您也将从 for 退出。
回答by Michael Berry
From a purist viewpoint, break arguably shouldn't be used. The point of a while loop is that you use the condition at the start of the loop to break out of it, and things can potentially get confusing if you start to flood your loop with break statements as oppose to getting the condition correct (which is a quick hack students may well be tempted to use if they can't work out how to do things the proper way!) The same goes for continue and returning in the middle of loops.
从纯粹主义者的角度来看,可以说不应该使用 break 。while 循环的重点是您在循环开始时使用条件来打破它,如果您开始用 break 语句淹没循环,而不是让条件正确(这是如果学生无法弄清楚如何以正确的方式做事,他们可能会很想使用快速 hack !)在循环中间继续和返回也是如此。
All these language features are there for a reason and yes, sometimes they're the best way of doing things. When just starting off however, the chances of you using them judiciously and properly are rare, they're more likely to be used as free "hack to get me out of jail without understanding how this thing works" cards. And that, I'd say, is a good enough reason to ban their use in basic programming courses.
所有这些语言特性的存在都是有原因的,是的,有时它们是做事的最佳方式。然而,当刚开始时,你明智和正确地使用它们的机会很少,它们更有可能被用作免费的“黑客让我在不了解它是如何工作的情况下出狱”卡。我想说,这是禁止在基本编程课程中使用它们的充分理由。
回答by James
You can early-terminate a for loop like this
您可以像这样提前终止 for 循环
for (int i = 0; i < SOMELIMIT && (!found); ++i) {...}
回答by BalusC
I'd imagine that your tutor wanted that you use the break condition in the condition part of the for loop. You need to declare this condition before the loop and change it inside the loop.
我想你的导师希望你在 for 循环的条件部分使用中断条件。您需要在循环之前声明此条件并在循环内更改它。
boolean stop = false;
for (...; ... && !stop; ...) {
...
if (...) {
stop = true;
}
}
回答by Richard H
break
and return
are not the same. break
will halt the execution of the inner-most loop, return
will return from the current method - ie nothing more in the method will be executed. As far as I know there's nothing wrong with using break in a loop; presumably this is an artificial requirement in order to get you to think of alternative logic. And there's nothing wrong with using a return
either; this will save you from horrible nested conditionals (if
clauses).
break
并且return
不一样。break
将停止最内层循环的执行,return
将从当前方法返回 - 即方法中的任何内容都不会被执行。据我所知,在循环中使用 break 没有错;大概这是一个人为的要求,目的是让您考虑替代逻辑。使用 areturn
也没有错;这将使您免于可怕的嵌套条件(if
子句)。
回答by Heinzi
Ifyou are not allowed to use break
, then it makes sense not to use return
as well, since every loop with break
can be rewritten as a loop with return
(by outsourcing it into a separate function).
如果不允许使用break
,那么最好不要使用return
,因为每个循环 withbreak
都可以重写为循环 with return
(通过将其外包到一个单独的函数中)。
From a non-homework point of view, break
(and return
) are very useful language features which are usually notconsidered bad style (of course, every language construct can be abused to write bad code).
从非作业的角度来看,break
(和return
)是非常有用的语言特性,通常不被认为是糟糕的风格(当然,每个语言结构都可以被滥用来编写糟糕的代码)。
In your homework scenario, however, I guess it would defeat the point of the homework to just "workaround" the missing break
by using return
. You should think of an alternative way to solve your task.
但是,在您的作业场景中,我想break
通过使用return
. 您应该想出一种替代方法来解决您的任务。
I tried to put a boolean operator in the while loop that controls the for loop but that doesn't control what goes on inside the for loop until the for loop gets to the end.
我试图在 while 循环中放置一个布尔运算符来控制 for 循环,但它不控制 for 循环内部发生的事情,直到 for 循环结束。
That's true, but, by using the if
statement, you can also execute/not execute code insidethe loop depending on your boolean.
这是真的,但是,通过使用该if
语句,您还可以根据您的布尔值在循环内执行/不执行代码。