I think removing the break
can be a good idea, but not to save lines of code.
The advantage of writing it without break
is that the post-condition of the loop is obvious and explicit. When you finish the loop and execute the next line of the program, your loop condition i < array.length && !condition
must have been false. Therefore, either i
was greater than or equal to your array length, or condition
is true.
In the version with break
, there’s a hidden gotcha. The loop condition says that the loop terminates when you’ve run some other code for each valid array index, but there is in fact a break
statement that could terminate the loop before that, and you won’t see it unless you review the loop code very carefully. And automated static analyzers, including optimizing compilers, could have trouble deducing what the post-conditions of the loop are, too.
This was the original reason Edgar Dijkstra wrote “Goto Considered Harmful.” It wasn’t a matter of style: breaking out of a loop makes it hard to formally reason about the state of the program. I have written plenty of break;
statements in my life, and once as an adult, I even wrote a goto
(to break out of multiple levels of a performance-critical inner loop and then continue with another branch of the search tree). However, I am far more likely to write a conditional return
statement from a loop (which never runs the code after the loop and therefore can’t muck up its post-conditions) than a break
.
Postscript
In fact, refactoring the code to give the same behavior might actually need more lines of code. Your refactoring could be valid for particular some other code or if we can prove that condition
will start off false. But your example is equivalent in the general case to:
if ( array.length > 0 ) {
// Some other code.
}
for ( int i = 1; i < array.length && !condition; i++ ) {
// Some other code.
}
If some other code isn’t a one-liner, you might then move it to a function so as not to repeat yourself, and then you’ve very nearly refactored your loop into a tail-recursive function.
I recognize this was not the main point of your question, though, and you were keeping it simple.
condition
in particular is.for(int i=0;i<array.length && !condition;i++)
is relatively uncommon and may be overlooked by someone just skimming the code; this might be a good use case for awhile
ordo while
loop, which more often have multiple break conditions in the loop definition.