As it turns out, at least one legitimate use exists for the notorious GOTO statement: breaking out of nested loops. Knowing from first-hand experience the problems that could be caused by "goto programming", I hadn't written a goto in 25 years. Recently, however, when trying to a write function with nested loops, it dawned on me that the most elegant solution would indeed involve a goto, at least when using C#. In fact, Microsoft's C# reference guide specifically recommends using a "goto" when exiting an inner loop, I later found out. (Maybe I ought to be reading Microsoft's online docs more often.)
In reviewing Steve McConnell's Code Complete (Second Edition), as I always do when confronting fundamental coding challenges, I was surprised to find only the vaguest of advice regarding "goto"--never say never, use your head, etc. Earlier in his book, McConnell does mention a Java-only approach. Java, which doesn't implement goto, actually has the nifty solution of named blocks, allowing you to end a break statement with the name of a block. I think this is superior than using a goto, but Java seems to be the only language with this feature.
Another author I consulted in this regard was Jeff Atwood. Atwood also describes beneficial situations for using goto, but in the only in the context of an "early return," rather than as a solution specifically for exiting nested loops. On the other hand, I really like Atwood's description of "return" and "exit" as being merely tightly scoped goto's.
No comments:
Post a Comment