On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
<sr******@no.spam.here-webworks-software.comwrote:
>
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
>Personally, I'm not of the mind that "goto" statements are inherently
bad. They certainly can be misused, and may well be misused much more
than other language constructs. But they also have their place (and I
don't just mean as a replacement for falling through in "case"
statements :) ).
Would you mind providing one such example?
Well, one common scenario is error-handling. In some cases, it makes
sense to have a single exit point in a method so that things can be
cleaned up in a single block of code rather than repeating that code, or
some subset, throughout the method. Using a "goto" statement allows you
to place that cleanup in a single place (I generally put it at the end of
the method), jumping to it on an error, and otherwise falling straight
through.
Nesting a bunch of "if()" statements can accomplish the same thing, but it
can create a difficult-to-read pattern of indentation. Using a "goto"
provides a lot of the same readability benefits that using exceptions for
failures can as well.
Are there other ways to do that? Sure, especially in C# (which has
"using" as well as exceptions). But those alternatives don't always
result in code that's as readable. And does the presence of those
alternatives mean that a "goto" statement is bad? No, not at all. Only
someone who had a blanket objection to using a "goto" statement for the
sake of the objection would say it was.
The fact is, even if you never write a "goto" statement, you use "goto"s
all the time. As long as you're keeping the code structured as you use a
"goto" statement, you haven't done anything the compiler wouldn't do
anyway. And if the use of the "goto" makes the code more readable, then
that's an advantage over shoe-horning your code into whatever alternative
the language would require to accomplish the same thing.
Pete