Friday, October 17, 2008

Hatin' on GOTO

So, it's general consensus that the GOTO statement (in any form) is evil, wrong, bad, no-no, etc. There's a fairly famous piece by Edsger Dijkstra entitled Go To Statement Considered Harmful in which he asserts that "the go to statement should be abolished from all 'higher level' programming languages."

There are a myriad of evil uses for the GOTO statement, in any language, it's true. My early days of programming were riddled with spaghetti code issues, especially once any of my far-too-ambitious projects attained a sort of critical mass. I remember in my early days of QuickBasic getting to around 15k lines of code (all in one huge Sub) being absolutely mystified as to why I could never finish anything...

I eventually grew up a bit, and as I encountered Visual Basic (at around version 3) I came to much the same conclusion as Mr. Dijkstra did; that the GOTO statement was the single greatest cause of error and confusion in software programming.

Looking back now, however, that might have been an error.

The problem isn't necessarily with the GOTO statement in and of itself, but rather with the willingness of the programmer to use the GOTO statement as a quick-fix way to get out of a sticky situation. In my QB days I indulged in this particular sin with impunity, only to wonder why my projects self-destructed not even a third of the way in.

The crime I committed was not in using GOTO, but rather in using GOTO incorrectly, and for incorrect uses. GOTO for me was a hammer, and all my program logic flow problems were nails - I wasn't shy in applying my tool - however to place the blame for my failings on the GOTO statement is a deception.

GOTO is a tool. It is a useful tool, sharp, though perhaps diminished in this age of WHILEs, DOs, FOREACHes, and the like, but still useful nonetheless. Be aware of its danger, however, in that it allows you to fall into your own traps. But should it be abolished because it is such a sharp tool?


Ray Vega said...

GOTOs should not be abolished. I agree with you that it is simply a tool and that it should be the programmer's decision how and when it can be used. (hopefully, sparingly :-) )

Amazingly enough, PHP recently added GOTO to the language. Yup, PHP did not have gotos at all until now. It is surprising given, as you stated in your post, the long history of it being viewed as an unneeded and dangerous feature of most languages. Despite the potential controversy, obviously someone thought it provided some value to PHP even after 15 years of its existence without it.

Great programming languages should provide as much freedom to a programmer as
it can. This means good or bad gotos should be allowed. For example, Lisp has always had continuations which behave like gotos and is considered one of the features that makes Lisp so powerful.

Erik said...

Just to prove how PHP-ignorant I am, I had no idea they didn't have GOTO until recently. =X Thanks. =)