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 wa
You can early-terminate a for loop like this
for (int i = 0; i < SOMELIMIT && (!found); ++i) {...}
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
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.
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.
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.