Re: Ziplock bags considered harmful? Message #15 Posted by Frank Wales on 5 Mar 2003, 4:37 p.m., in response to message #13 by GE (France)
I tend to favour gotos when I'm defining something like a state machine, where I think if() or switch() statements and state variables might cloud what's going on. I'll also use them for performance where I need it.
So, I'm perfectly happy to use gotos where they're appropriate, but I don't see that this is an example of that. Is this not equivalent to the example you cite?
doAstuff...;
if (!error) {
doBstuff...;
if (!error) {
doCstuff...;
cleanUpC...;
}
cleanUpB...;
}
cleanUpA...;
Most OOP languages support exception handling, which is specifically intended to let the programmer deal with run-time errors and other unusual conditions in a controllable way, and to allow them to use special syntax to indicate that that's what they're doing. So, you might have something like:
try {
doAStuff...;
try {
doBStuff...;
try {
doCStuff...;
}
finally {
cleanUpC...;
}
}
finally {
cleanUpB;
}
}
catch (error) {
...handle the error, if you like...
}
finally {
cleanUpA;
}
Just to be different, I've thrown in some actual error handling, although that's not necessary.
Ultimately, the two problems with goto that give some people in the software realm apoplexy are:
- it increases the chances that control will jump to a piece of code that's not ready to take over, because (for example) variables are uninitialised or out of scope, or the stack is in an untidy condition;
- it clouds the reason why program control is being transferred elsewhere, which can be made more obvious by the use of all the other keywords that are either 'restricted goto' (such as a switch statement) or 'goto with knobs on'
(such as subroutine calling).
This second point is especially important, because it increases the comprehensibility of a piece of code, and ultimately most programs are coded for human readability first, and machine readability second. It also makes it easier to analyse the code for flaws, and makes refactoring tools more useful.
Note also that the Dijkstra's proscription of goto originated in the 1960s, when uncontrolled gotos just had to be used a lot, because commonplace programming languages didn't have a lot of other options for transferring control. In part, we now have many features in our programming languages, such as lexical scope, switch statements, continuations, exception handling, and type-based method dispatch, because of the discussion he started.
|