Break statements and why I’ll dock marks for them

Right, break statements and why they’re bad.

Generally it’s indicating you’ve got a problem with the flow of your program and you may need to restructure.

Imagine the following that hunts for a number, it’s an odd program, but it’s an illustration.

# x = some number you're hunting for
x = 56
for i in range(100):
if i == x:

print("Found x!")
break
else:
print(i, "isn't x")

This program will loop up until 56. If you’re trying to debug a program 100x more complex then this and it has a similar format over 100 lines, you’ve got a loop which says it’s counting from 0 to 100, yet it’s only going to 56. To figure out why you’ve got to hunt through and find a break statement and figure out what it applies to – which bit it’s ‘break’ing.

Consider the alternative:

x = 56
i = -1
while i != x:
i = i + 1
if i == x:
print("Found x!")
else:

print(i, "isn't x")

These programs are identical, the second has a bit more faff with declaring and incrementing i, but it’s a conditional loop. The first one is an unconditional loop you’re trying to hack into a conditional loop.

If you’re in a sodding hotel in Africa and hunting through lines of code at 3 in the morning trying to find an issue so you can fix the problem and actually go home but the developers have gone home because “it’s gone 4:30pm and they wanted to miss the traffic” then you will appreciate the second being easier to understand and debug than the first.

Look at the condition on the first, it’s looping to 100….but the result is that it doesn’t.

Look at the condition on the first, it’s looping to x…..and that’s what’s happening. Clarity.

Hopefully that’s fairly clear. Generally I appreciate people finding solutions, but break is one command that I think shouldn’t exist as it’s just a plaster for bad structure.

People will have different view points, people will say that I’m wrong, and I respect that, provided there’s justification. I can accept there are some circumstances where a break statement is good, but they’re specifics, I don’t believe it should be used as a general tool to be wielded with frequency.

One Reply on “Break statements and why I’ll dock marks for them”

Leave a Reply

Your email address will not be published. Required fields are marked *