Archive - Originally posted on "The Horse's Mouth" - 2008-08-06 06:32:19 - Graham Ellis
The "goto" statement - in languages that still support it - is regarded with disdain by Computer Scientists as it makes for spaghetti code - hard to follow and going all over the place!
In some ways, loop controls "break" and "continue" ("last", "next" and "redo" in Perl; "next", "redo", "retry" and "break" in Ruby) are also forms of the goto. They are not as bad in that they only jump within a limited area, but on the other hand many forms don't involve labels so that there's no clue at the destination point in your code that it's an arrival point.
Having slagged off these statements (and in reality I'm being a pedantic computer scientist by doing so - I use them personally from time to time!) I had better off you the alternative. Written on yesterday's Lua course as a demonstration - here's a while loop that has an ugly break in it ...
j=14
while 1 do
print (j)
if j > 20 then break end
j = j + 1
end
print ("done")
... and here's the alternative using a control variable. ...
j=14
running = true
while running do
print (j)
if j > 20 then
running = false
else
j = j + 1
end
end
print ("done")
That code being longer, but purer and easier to maintain.