简体   繁体   English

使用'return'打破Java中的for循环是不好的风格?

[英]Is it bad style to use 'return' to break a for loop in Java?

I'm doing a project with basic Java for a CS class. 我正在为CS类做一个基本Java项目。 The project has a for loop nested inside a while loop. 该项目有一个嵌套在while循环中的for循环。

I am not allowed to use break as a way of ending a for loop early. 不允许使用break作为早期结束for循环的方法。 I found out that return seems to have the same effect as break . 我发现return似乎和break有同样的效果。 Is it bad style to use return as a way to break the loop? 使用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. 299/01/11更新:非常感谢大家的评论。 I found it really helpful to read through all the debates. 我发现阅读所有辩论真的很有帮助。

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'循环中设置布尔值的建议确实很有帮助,因为我不知道你能做到这一点。

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 nothing unreadable 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 here for some good advice regarding these issues outside of educational institutions. 请参阅此处 ,了解有关教育机构以外的这些问题的一些好建议。

First of all, it's not a bad style to use break , if you use it judiciously. 首先,这不是一个糟糕的风格来使用break ,如果你明智地使用它。
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编码(因为很多人,尤其是初学者,倾向于'过度使用'),但没有理由完全禁止它。

Is it bad style to use return as a way to break the loop? 使用return作为打破循环的一种方式是不好的风格?
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. 整个问题非常主观,因此我无法告诉他。

But again, regardless of what your professor sais, using return in a loop is not a bad style. 但同样,无论你的教授sais是什么,在循环中使用return 并不是一种糟糕的风格。

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 . 因此,如果在循环中使用返回令您(或您的老师)感到担忧,您(或他)可以在这里查看

To answer your question. 回答你的问题。 In my (and not only my) opinion using a return in a loop is definitely OK. 在我(而不仅仅是我的)意见中使用循环返回绝对可以。

Do note however that overusing it might decrease code readability (see linked answer for details/examples). 但请注意,过度使用它可能会降低代码的可读性(有关详细信息/示例,请参阅链接的答案)。

Also does it matter if 'return' doesn't return anything? 如果'return'没有返回任何东西也有关系吗?

That depends on your method's return type. 这取决于您的方法的返回类型。 if the return type is void, a return clause must be empty: 如果返回类型为void,则return子句必须为空:

return;

otherwise, a return clause must return the required type, eg 否则,return子句必须返回所需的类型,例如

return true; // legal for boolean return type
return null; // legal for all object types
return "Hello"; // legal if return type is String

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. while循环的要点是你使用循环开始时的条件来摆脱它,如果你开始用break语句填充你的循环而不是让条件正确(这是一个快速的黑客学生很可能会被诱惑使用,如果他们无法解决如何以正确的方式做事!)同样的事情继续和循环中间返回。

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. 而且,我认为,这是一个足以让他们在基础编程课程中使用的理由。

break and return are not the same. breakreturn都不一样。 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. break将暂停最内层循环的执行, return将从当前方法返回 - 即该方法中不再执行任何操作。 As far as I know there's nothing wrong with using break in a loop; 据我所知,在循环中使用break没有任何问题; 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; 使用return也没有错; this will save you from horrible nested conditionals ( if clauses). 这将使您免于可怕的嵌套条件( if条款)。

If you 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也是有意义的,因为每个带break循环都可以重写为带有return的循环(通过将其外包到一个单独的函数中)。

From a non-homework point of view, break (and return ) are very useful language features which are usually not considered 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 . 然而,在你的家庭作业场景中,我想它会break作业的重点,只是通过使用return来“解决”缺失的break You should think of an alternative way to solve your task. 你应该想办法解决你的任务。

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 inside the loop depending on your boolean. 这是真的,但是,通过使用if语句,您还可以根据您的布尔值执行/不执行循环内部的代码。

您可以像这样提前终止for循环

for (int i = 0; i < SOMELIMIT && (!found); ++i) {...}

I'd imagine that your tutor wanted that you use the break condition in the condition part of the for loop. 我想你的导师想要你在for循环的条件部分使用break条件。 You need to declare this condition before the loop and change it inside the loop. 您需要在循环之前声明此条件并在循环内更改它。

boolean stop = false;

for (...; ... && !stop; ...) {
    ...
    if (...) {
        stop = true;
    }
}

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设置为停止时,您也将退出for。

您将获得相同的结果,但代码质量和易读性将降低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM