Goto Pro's and Con's 
Author Message
 Goto Pro's and Con's

After writing way over 100,000 lines of C with absolutely no GOTOs,
I have had the strange, unexpected experience of becoming a convert to
using GOTOs in error management.  This resulted when my partner and I
developed a (beautiful) 20,000 line program in C which uses GOTOs
(sometimes with setjmp/longjmp) to achieve comprehensive error
management and reporting, with full cleanup after errors (what C++ would
call exception-safe code), at almost no cost in code volume or
complexity -- a striking improvement over industry standards.

The drive to eliminate GOTO has two sources.  The more commonly
mentioned of these is that unrestricted use of GOTO can result in bad
(or even horrible) code -- and in the hands of students, does so with
distressing frequency.  This seems beyond dispute (although how people
define "bad" or "horrible" is interesting).

The less commonly mentioned argument for the elimination of GOTO is
that GOTO is an impediment to the development of programs to prove the
correctness of programs.  The same argument was given as a reason to
eliminate recursion (!).  However, as proofs of program correctness
have so far had little commercial (or other) significance, this
argument for the elimination of GOTO does not seem particularly
compelling.

GOTO, per se, is not inherently good or evil -- it is just a statement
in the language.  It can be used in a stylized, disciplined way to be
*exactly* equivalent to "modern" flow-control constructs (e.g., do,
while, and switch statements); and if restricted by convention (and
religious fervor) to such constructs, is no more good or bad than they
are.

An oft-mentioned fact is that GOTOs can always be replaced with other
flow-control constructs.  But consider transforming a program (or a
single subroutine) into a state machine, where the state consists of
the next line to execute (plus any additional information required),
with no other flow-control constructs.  This can always be done.
Implement this as:
    switch (nextLineToExecute) {
        ...;
        /* set up new value for nextLineToExecute */
    }
This is perfectly "structured", yet embeds all the complexity of the
original code -- even if the original is classic GOTO-ridden spagetti
code.  Clearly, eliminating GOTOs in this fashion serves nothing; the
problem lies elsewhere.

I submit that what is really at issue is the code complexity.
Controlling complexity goes to the heart of the entire structured and
object oriented programming movements.  And while GOTO statements, break
statements, and multiple returns from subroutines go against structured
programming dogma, the evidence of our eyes is that these can be used
to simplify code.

Such simplification is sorely needed with error management and
reporting code (something sadly lacking in many programs).  There are
many stories of large systems being dominated by error management; I
have seen one such system where unwillingness to use GOTOs or multiple
returns from subroutines caused the system to require three time as much
code as it would have otherwise (shocking, but true).  The judicious
use of "goto ERR_EXIT" allows the programmer to focus on the normal
execution of the code, knowing that any necessary cleanup will be done
following the ERR_EXIT label.  In addition to potentially great
simplifications in the code, this has the benefit of centralizing this
cleanup code.

The exception handling of C++, if implemented and used correctly, can
do exactly the same thing I have seen done so well in C -- and with
considerably more ease.  But C does not offer language support for
exceptions (nor, for that matter, do some implementations of C++).
Therefore, since C++ is supposed to be (more or less) a superset of C,
it seems grossly inappropriate to suggest removing GOTO from C++, given
that this feature of C can be so very useful.

[End of flamebait; now donning asbestos suit...]




Sat, 22 Feb 1997 01:59:57 GMT  
 Goto Pro's and Con's


Quote:
>After writing way over 100,000 lines of C with absolutely no GOTOs,
>I have had the strange, unexpected experience of becoming a convert to
>using GOTOs in error management.  This resulted when my partner and I
>developed a (beautiful) 20,000 line program in C which uses GOTOs
>(sometimes with setjmp/longjmp) to achieve comprehensive error
>management and reporting, with full cleanup after errors (what C++ would
>call exception-safe code), at almost no cost in code volume or
>complexity -- a striking improvement over industry standards.

Anyone that never does somthing in a computer language is placing unessary
constraints on themselves. Goto, recursion, and longjmp are all useful tools
like any sharp tool you can cut yourself with them. If you use good names
goto can be much clearer than an if statemnt.

When writing any code compermises are made. In my case in large models and
embeded systems speed is usualy the first concren and size then next and
niceties last. Most of my code is for research and not much is reused. When
I am writing code that will be used by less experianced C programers I make
and effort to make it simpler and eaiser to use than I would for someone
that has programed in C for years.

Your milage may vary,
Gordon



Sat, 22 Feb 1997 03:06:48 GMT  
 Goto Pro's and Con's

<stuff deleted>
: I submit that what is really at issue is the code complexity.
: Controlling complexity goes to the heart of the entire structured and
: object oriented programming movements.  And while GOTO statements, break
: statements, and multiple returns from subroutines go against structured
: programming dogma, the evidence of our eyes is that these can be used
: to simplify code.

: Such simplification is sorely needed with error management and
: reporting code (something sadly lacking in many programs).  There are
: many stories of large systems being dominated by error management; I
: have seen one such system where unwillingness to use GOTOs or multiple
: returns from subroutines caused the system to require three time as much
: code as it would have otherwise (shocking, but true).  The judicious
: use of "goto ERR_EXIT" allows the programmer to focus on the normal
: execution of the code, knowing that any necessary cleanup will be done
: following the ERR_EXIT label.  In addition to potentially great
: simplifications in the code, this has the benefit of centralizing this
: cleanup code.
<stuff deleted>

Interesting.  I have had similar experiences in fortran (no flames please,
I've been converted) when I first attempted to deal with error control way
back when I was a programming newbie.  I thought the fault lay in my
inability as a programmer.  Rich, could you follow-up with a real example
or two of code being dominated by error management along with the simplified
GOTO containing code.  I would really like to see how GOTOs would manifest
in a piece of professionally written code and such a posting may lend
support to your arguments although please note that I am not exactly on
your side.

                                        Skeptical but open-minded,

                                        Kevin

--
Kevin Ternes               Department of Materials Science and Engineering

                           Blacksburg VA  24061-0237   USA
          thesis:  http://www.vt.edu:10021/vizlab/class/ternes.html



Sat, 22 Feb 1997 03:20:31 GMT  
 Goto Pro's and Con's

Quote:
(Kurt Watzka) writes:

[snip]
>> >From practical experience (not by necessity), the presence of a goto
>> >indicates a function that wasn't well thought out.  The program was
designed
>> >at the keyboard.  When the programmer realized that--Oops!--he or she
needs
>> >to get from this statement over here to that statement over there, the
>> >shortest line between two points is a goto.

>> >I believe that in some rare cases (exception handling is often cited as
the
>> >prototypical application), a goto is a good thing.  I've probably used a
goto
>> >in C twice; likewise with setjmp()/longjmp().  They should be in your
tool
>> >chest, but should be in the bottom draw under many other tools.

>> In my experience, exception handling is not a rare case.  Consider the
>> following pices of pseudo-code:

[snip: code that uses nested ifs]
[snip: code that uses gotos instead]

Quote:
>> I would not dare to say that one of the two idoms is a sign that
>> the "program was designed at the keyboard". Both express the same
>> concept, i.e. that you need all resources to perform the action
>> and you must not deallocate resources that are not allocated.

I would say that the latter is poorly written, regardless of how it came to
be that way.

You have purposely written a straightforward example.  The gotos I see in
code are rarely so pristine.  From the context within which I almost always
see gotos, it is evident that the programmer painted him or herself into a
corner.  Rather than rethink the solution or having had thought it out in
advance, the programmer takes the easy way out and does a goto, maintenance
be damned.


Sent from Oregon Telcom



Sun, 23 Feb 1997 10:42:22 GMT  
 Goto Pro's and Con's

Quote:
(Richard L. Miller) writes:
>> GOTO, per se, is not inherently good or evil -- it is just a statement
>> in the language.  It can be used in a stylized, disciplined way to be
>> *exactly* equivalent to "modern" flow-control constructs (e.g., do,
>> while, and switch statements); and if restricted by convention (and
>> religious fervor) to such constructs, is no more good or bad than they
>> are.

The line goes like this: "Gotos are okay if used wisely."  While some
programmers may actually use gotos wisely, most of the time gotos are used
quite carelessly.  Maybe once or twice have I seen well written code use a
goto.  Usually, where there's a goto, there's trouble.

From practical experience (not by necessity), the presence of a goto
indicates a function that wasn't well thought out.  The program was designed
at the keyboard.  When the programmer realized that--Oops!--he or she needs
to get from this statement over here to that statement over there, the
shortest line between two points is a goto.

I believe that in some rare cases (exception handling is often cited as the
prototypical application), a goto is a good thing.  I've probably used a goto
in C twice; likewise with setjmp()/longjmp().  They should be in your tool
chest, but should be in the bottom draw under many other tools.


Sent from Oregon Telcom



Sat, 22 Feb 1997 12:57:05 GMT  
 Goto Pro's and Con's

Quote:


>(Kurt Watzka) writes:

>[snip]
>>> In my experience, exception handling is not a rare case.  Consider the
>>> following pices of pseudo-code:
>[snip: code that uses nested ifs]
>[snip: code that uses gotos instead]
>>> I would not dare to say that one of the two idoms is a sign that
>>> the "program was designed at the keyboard". Both express the same
>>> concept, i.e. that you need all resources to perform the action
>>> and you must not deallocate resources that are not allocated.

>I would say that the latter is poorly written, regardless of how it came to
>be that way.

>You have purposely written a straightforward example.  The gotos I see in
>code are rarely so pristine.  From the context within which I almost always
>see gotos, it is evident that the programmer painted him or herself into a
>corner.  Rather than rethink the solution or having had thought it out in
>advance, the programmer takes the easy way out and does a goto, maintenance
>be damned.

I worked on a project once in which the comma operator, typedefs and
function return values were banned because the Project Ruler had decided
that people were too likely to misuse or misunderstand them.

The point, of course, is to not throw something out because it might be
misused, rather provide guidlines as to how "problem" features are to be
used, if they are.

To say that a feature should be banned because programmers can abuse it,
leads directly to the elimination of most of the C langugage. Whoever is
managing programmers is responsible for training and directing those
programmers, not for cutting off their options.

I can think of a number of times that I've had to write awkward,
convoluted code, the only purpose of which was to avoid a goto. In my
strictly personal opinion, that's silly.

--
Joe Halpin

---------------------------------------------------------------------------



Mon, 24 Feb 1997 10:10:05 GMT  
 Goto Pro's and Con's


Quote:
>GOTO, per se, is not inherently good or evil -- it is just a statement
>in the language.  It can be used in a stylized, disciplined way to be
>*exactly* equivalent to "modern" flow-control constructs (e.g., do,
>while, and switch statements); and if restricted by convention (and
>religious fervor) to such constructs, is no more good or bad than they
>are.

It is generally accepted that gotos have their place. However if a
construct can be naturally written with for, while etc. it is
more readable and maintainable to do so because they mark more clearly
how the flow of program execution proceeds. A goto is still at the end of
the day just a branch to a label which imposes few restrictions as to where
in the function that label may be. Conversely when you see a label in
a function its not so easy to spot all points in the function that will
branch to it. The structured constructs tie these down much more rigorously
which makes code maintenance easier. However these restrictions means there
are times when a problem can't be modelled cleanly using structured constructs
(and error handling is probably the most common example) and using simple
code with gotos is much clearer than complex/unnatural code that avoids them.

--
-----------------------------------------


-----------------------------------------



Sat, 22 Feb 1997 19:28:16 GMT  
 Goto Pro's and Con's

Quote:

>The line goes like this: "Gotos are okay if used wisely."  While some
>programmers may actually use gotos wisely, most of the time gotos are used
>quite carelessly.  Maybe once or twice have I seen well written code use a
>goto.  Usually, where there's a goto, there's trouble.
>From practical experience (not by necessity), the presence of a goto
>indicates a function that wasn't well thought out.  The program was designed
>at the keyboard.  When the programmer realized that--Oops!--he or she needs
>to get from this statement over here to that statement over there, the
>shortest line between two points is a goto.
>I believe that in some rare cases (exception handling is often cited as the
>prototypical application), a goto is a good thing.  I've probably used a goto
>in C twice; likewise with setjmp()/longjmp().  They should be in your tool
>chest, but should be in the bottom draw under many other tools.

In my experience, exception handling is not a rare case. Consider the
following pices of pseudo-code:

a:

  set error indicator to true;
  allocate resource 1;
  if ( successful )
  {
    allocate resource 2;
    if ( successful )
    {
      allocate resource 3;
      if ( successful )
      {
        use resources;
        set error indicator to false;
        deallocate resource 3;
      }
      deallocate resource 2;
    }
    deallocate resource 1;
  }
  return error indicator;

b:

  set error indicator to true;
  allocate resource 1;
  if ( !successful )
    goto no_resource_1;
  allocate resource 2;
  if ( !successful )
    goto no_resource_2;
  allocate resource 3;
  if ( !successful )
    goto no_reource_3;

  use resources;
  set error inidator to false;

  deallocate resource 3;
no_resource_3:
  deallocate resource 2;
no_resource_2:
  deallocate resource 1;
no_resource_1:
  return error indicator;

Both idioms express the same concept:

  allocate resources;
  use resources;
  deallocate resources;

I would not dare to say that one of the two idoms is a sign that
the "program was designed at the keyboard". Both express the same
concept, i.e. that you need all resources to perform the action
and you must not deallocate resources that are not allocated.

--
| Kurt Watzka                             Phone : +49-89-2180-2158




Sat, 22 Feb 1997 17:59:47 GMT  
 Goto Pro's and Con's

Quote:
>I submit that what is really at issue is the code complexity.
>Controlling complexity goes to the heart of the entire structured and
>object oriented programming movements.  And while GOTO statements, break
>statements, and multiple returns from subroutines go against structured
>programming dogma, the evidence of our eyes is that these can be used
>to simplify code.

This is undeniably true.  The careful use of GOTO can shrink code
dramatically.    However there is a cost.  The reason the code shrinks
is that you *assume* that you can branch to an area of common code in
all circumstances; and that this fact will remain true throughout the
lifetime of the product.

Such assumptions create dependencies.  The common code depends upon
conditions set up by the branching code, and the branching code
depends upon operations preformed by the common code.

Managing these dependencies during initial project development is
usually not too difficult.  But as the program evolves over its
lifecycle, counter examples will be created.  The strategy will be to
use flags and other context sensitive means to "condition" the common
code to preform correctly.  Thus even more dependencies will be
created.  The end is usually sad.

Let me make a point.  You said that "controlling complexity goes to
the heart of OO".  I agree.  However you have implied that complexity
is the equivalent of code size.  I disagree.  And to back that up I
have the observation that OO programs usually have more lines than
equivalent procedural programs do -- at first.  At the end of their
lifecycle, the opposite is generally true; that OO programs will have
fewer lines then their equivalent procedural programs do.

Why?  Because the complexity being managed is not the instantaneous
complexity of the current code, it is the complexity of the lifecycle
of the product.  Often in OOD we add lines of code in order to build
an infrastructure that will be stable throught the anticipated
lifecycle.  That infrastructure breaks dependencies that would exist
in the equivalent procedural program.

Using structured techniques has a larger short term cost than breaking
structure and using gotos.  Using OO techniques has a larger short
term cost than breaking the object model and using procedural
techniques.  The two trade-offs are exactly the same.  And the long
term costs of both shortcuts can be extreme.  Short term thinking has
utterly killed many very promising startups.

--
Robert Martin       | Design Consulting   | Training courses offered:

2080 Cranbrook Rd.  | Tel: (708) 918-1004 |   Object Oriented Design
Green Oaks IL 60048 | Fax: (708) 918-1023 |   C++



Mon, 24 Feb 1997 02:28:26 GMT  
 Goto Pro's and Con's

Quote:

>However these restrictions means there
>are times when a problem can't be modelled cleanly using structured constructs
>(and error handling is probably the most common example) and using simple
>code with gotos is much clearer than complex/unnatural code that avoids them.

I submit that the consistent use of terms such as 'natural' and
'clean' instead of very specific terms, indicates that these are
subjective issues that cannot be backed up with any kind of
quantitative analysis.    

On the other hand, modeling programs as blocks with a single entrance
and a single exit can be quantitatively described, and the advantages
can be quantitatively expressed.  i.e. the number of implicit and
explicit dependencies per block are minimized.

When a programming style depends upon a subjective view, there will be
people that agree for subjective reasons, and other people who
disagree for subjective reasons.  And the debate will continue
forever.  When a programming style depends upon quantitative analysis,
it requires another quantitative analysis (i.e. a proof) to displace
that style.  

i.e. no matter how many people say that structured code for error
management is ugly or unclean or unnatural, I will continue to use it
until somebody shows me another style that has a better dependency
structure (e.g. OO).

--
Robert Martin       | Design Consulting   | Training courses offered:

2080 Cranbrook Rd.  | Tel: (708) 918-1004 |   Object Oriented Design
Green Oaks IL 60048 | Fax: (708) 918-1023 |   C++



Mon, 24 Feb 1997 02:36:03 GMT  
 Goto Pro's and Con's

Quote:
(Robert Martin) writes:

|> i.e. no matter how many people say that structured code for error
|> management is ugly or unclean or unnatural, I will continue to use it
|> until somebody shows me another style that has a better dependency
|> structure (e.g. OO).

I agree.  I think that most of the time people find structured code
unnatural for error management, it is because they have first
developped a structure without error management, and then attempted to
add the error management as an after thought.

If error handling is considered a fundamental part of the algorithm,
designed in from the start as being essential, there is no more reason
to use an unstructured approach for it than for any other fundamental
part of the algorithm.  Regretfully, all of the books on algorithmic
analysis that I am familiar with seem to ignore the fact that errors
can and will occur.  Take any algorithm book you like and look up the
algorithm for balanced trees (AVL trees or red-black trees, it doesn't
matter).  Now try and imagine how the algorithm will work if the data
in the tree are IEEE doubles.  And some of the nodes contain NaN's.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                              -- Beratung in industrieller Datenverarbeitung



Mon, 24 Feb 1997 21:48:23 GMT  
 Goto Pro's and Con's

Quote:
> After writing way over 100,000 lines of C with absolutely no GOTOs,
> I have had the strange, unexpected experience of becoming a convert to
> using GOTOs in error management.  This resulted when my partner and I
> developed a (beautiful) 20,000 line program in C which uses GOTOs
> (sometimes with setjmp/longjmp) to achieve comprehensive error
> management and reporting, with full cleanup after errors (what C++ would
> call exception-safe code), at almost no cost in code volume or
> complexity -- a striking improvement over industry standards.
> ...

I just about to ask about this--

What are standard or typical ways of using exceptions in C to manage errors?
I'm looking for a method that would be reasonably portable on Unix (Sun, HP,
IBM) and Windows-NT.

Daniel

--


        "They listen hard, and act like they care.
         How can they be so completely unaware
         Of the truth?  The answer is always denied me
         So I introduce 'em to the killer inside me." - MC 900 Ft. Jesus



Mon, 24 Feb 1997 03:44:32 GMT  
 Goto Pro's and Con's


Quote:
>I just about to ask about this--

>What are standard or typical ways of using exceptions in C to manage errors?
>I'm looking for a method that would be reasonably portable on Unix (Sun, HP,
>IBM) and Windows-NT.

>Daniel

There are various C exception handling packages that I have seen which
try to use a Lisp- or ML-like model.  Of these, the nicest I have seen
(and used) was written by Eric Roberts.  It was published in a DEC
research paper and is available by anonymous ftp.  It is fully
ANSI-compliant and portable to any ANSI C compiler.

For more information, check out labrea.stanford.edu, in the
/cs/teaching/eroberts/cslib directory.

-Jon



Mon, 24 Feb 1997 07:39:44 GMT  
 Goto Pro's and Con's

Quote:

> I worked on a project once in which the comma operator, typedefs and
> function return values were banned because the Project Ruler had decided
> that people were too likely to misuse or misunderstand them.

Typedefs were ruled _out_?  Strange.

Daniel
--


        "They listen hard, and act like they care.
         How can they be so completely unaware
         Of the truth?  The answer is always denied me
         So I introduce 'em to the killer inside me." - MC 900 Ft. Jesus



Mon, 24 Feb 1997 23:47:16 GMT  
 Goto Pro's and Con's
There is generally one situation when I use goto: When "break"
(or continue) wouldn't work since it is in an inner loop to the
one I want to "break".

This "goto" could have been avoided if it had been possible to
"label" loops in C, e.g. like below:

    How I do it                           How I'd like to do it
    =============================         =============================
    for (i = 0; i < n; i++)               for LOOP1: (i = 0; i < n; i++)
        for (j = 0; j < n; j++)               for (j = 0; j < n; j++)    
            if (f)                                if (f)
                goto LOOP1_EXIT;                      break LOOP1;
            else                                  else
                <do stuff>                            <do stuff>
    LOOP1_EXIT:

    while (a)                             while LOOP2: (a)
        switch (b) {                          switch (b) {
        case 0:                               case 0:
            goto LOOP2_EXIT;                      break LOOP2;
        case <do-stuff-values>:               case <do-stuff-values>:
            <do stuff>                            <do stuff>
            break;                                break;
        }                                     }
    LOOP2_EXIT:

Now, wouldn't the possibility to use this kind of syntax be a
nice (hypothetical :-) feature?

/SS



Tue, 25 Feb 1997 10:28:19 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. A use for GOTO (was Goto Pro's and Con's)

2. PL/I's leave (Was: Re: Goto Pro's and Con's)

3. in-reference-to: Goto Pro's and Con's

4. UNDOing (was Goto Pro's and Con's)

5. .PDB vs .DBG - Discussion of the Pro's and Con's

6. Arrays and Pointers, con't

7. Window's Service and Cons Application

8. Pros and Cons of register int

9. DataSet--pros and cons

10. Application config files - pros and cons

11. Labels .. Pros and Cons

12. Pros/Cons of J2EE + .NET (plus, java salaries are HOT)

 

 
Powered by phpBB® Forum Software