swegr‎ > ‎

break and continue



Dijkstra is against break:

features like break tend to sabotage the benefits of structured programming, and prevent the programmer from understanding the program as a composition of independent units. [2]

Mcconnel says the same

A loop with many breaks may indicate unclear thinking about the structure of the loop or its role in the surrounding code. Excessive breaks raises often indicates that the loop could be more clearly expressed as a series of loops. [1]

Use of break eliminates the possibility of treating a loop as a black box1. Control a loop's exit condition with one statement to simplify your loops. 'break' forces the person reading your code to look inside to understand the loop's control, making the loop more difficult to understand. [1]

As Mcconnel notes, the break in this loop means we can no longer treat the loop-body as a black box.

while (condition)
if (something) break;

You cannot factor that loop into:

while (condition) DoSomething();

Despite this, break is convenient for little mini-loops:

for person in queue:
    if person.name==”Fred”: break

this loop is a mess when expressed without break.
while (person and !person.name==”Fred) person=queue.pop()

even better than using break would be extracting a method and using early return
def find(target, sequence):
  for item in sequence:
    if item==target: return item
find(fred, queue)

note that early return and break are theoretically equivalent. So, there are exceptions to Mcconnel's advice, but these exceptions are best factored into tiny methods where the impact of the break is obvious.


Crawford said: "The continue statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove the continue statement." He's wrong.

Loops with continue can be factored into this form and thus the loop may be treated as a black box. Continue loops are good! Mcconnel and Dijkstra's arguments don't hold against continue loops.

who cares

the whole debate is moot. 'continue' can be exactly emulated by extracting your loop body into a method with early returns; 'break' can be exactly emulated by extracting the whole loop into a method with early returns. factor your code well and stop thinking about it.

1. McConnell, Steve. Code Complete, Second Edition. Microsoft Press © 2004. Chapter 16.2: Controlling the Loop.
: getz_so : http://stackoverflow.com/questions/216359