开发者

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

开发者 https://www.devze.com 2023-02-06 16:16 出处:网络
I\'m doing a project with basic Java for a CS class. The project has a for loop nested inside a while loop.

I'm doing a project with basic Java for a CS class. The project has a for loop nested inside a while loop.

I am not allowed to 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?

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.

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.

Also does it matter if return doesn't return anything?

299/01/11 Update: Thanks everyone so much for your comments. 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.

So I found the advice about setting a boolean in the 'for' loop really helpful, as I didn't know you could do that.


They'll only be equivalent if the first thing after breaking out of the loop is a return statement.

In any case, if your lecturer doesn't allow break, they probably won't allow return either.

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.

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.

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.
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.

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.

But again, regardless of what your professor sais, using return in a loop is not a bad style.


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?

That depends on your method's return type. if the return type is void, a return clause must be empty:

return;

otherwise, a return clause must return the required type, e.g.

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


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.


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.

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. 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).


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).

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).

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.

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.

That's true, but, by using the if statement, you can also execute/not execute code inside the loop depending on your boolean.


You can early-terminate a for loop like this

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. You need to declare this condition before the loop and change it inside the loop.

boolean stop = false;

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


You will get the same result but the code quality and legibility will decrease.

0

精彩评论

暂无评论...
验证码 换一张
取 消