I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

October 25, 2007

I'd Consider That Harmful, Too

One of the seminal papers in computer science is Edsger Dijkstra's 1968 paper GOTO Considered Harmful.

For a number of years I have been familiar with the observation that the quality of programmers is a decreasing function of the density of go to statements in the programs they produce. More recently I discovered why the use of the go to statement has such disastrous effects, and I became convinced that the go to statement should be abolished from all "higher level" programming languages (i.e. everything except, perhaps, plain machine code).

The abuse of GOTO is, thankfully, a long forgotten memory in today's modern programming languages. Of course, it's only a minor hazard compared to the COMEFROM statement, but I'm glad to have both of those largely behind us.

So then I typed GOTO 500 -- and here I am!

GOTO isn't all bad, though. It still has some relevance to today's code. Along with many other programmers, I always recommend using guard clauses to avoid arrow code, and I also recommend exiting early from a loop as soon as you find the value you're looking for. What is an early Return, or an early Exit For other than a tightly scoped GOTO?

foreach my $try (@options) {
  next unless exists $hash{$try};
  do_something($try);
  goto SUCCESS;
}

log_failure();

SUCCESS: ...

The publication of such an influential paper in this particular format led to an almost immediate snowclone effect, as documented on Wikipedia:

Frank Rubin published a criticism of Dijkstra's letter in the March 1987 CACM where it appeared as 'GOTO Considered Harmful' Considered Harmful. The May 1987 CACM printed further replies, both for and against, as '"GOTO Considered Harmful" Considered Harmful' Considered Harmful?. Dijkstra's own response to this controversy was titled "On a somewhat disappointing correspondence".

That's easily one of the funniest things I've ever read in Wikipedia. Who says computer scientists don't have a sense of humor? But I digress. Most software developers are probably familiar, at least in passing, with Dijkstra's GOTO Considered Harmful. But here's what they might not know about it:

  1. The paper was originally titled "A Case Against the Goto Statement"; the editor of the CACM at the time, Niklaus Wirth, changed the title to the more inflammatory version we know today.
  2. In order to speed up its publication, the paper was converted into a "Letter to the Editor".

In other words, Wirth poked and prodded the content until it became incendiary, to maximize its impact. The phrase "considered harmful" was used quite intentionally, as documented on the always excellent Language Log:

However, "X considered harmful" was already a well-established journalistic cliche in 1968 -- which is why Wirth chose it. The illlustration below shows the headline of a letter to the New York Times published August 12, 1949: "Rent Control Controversy / Enacting Now of Hasty Legislation Considered Harmful".

Rent Control Controversy / Enacting Now of Hasty Legislation Considered Harmful

I'm sure it's not the earliest example of this phrase used in a headline or title, either -- I chose it only as a convenient illustration of susage a couple of decades before the date of Dijkstra's paper.

Note that this example is also in the title of a slightly cranky letter to the editor - it's probably not an accident that the first example that came to hand of "considered harmful" in a pre-Dijkstra title was of this type.

So when you emulate the "considered harmful" style predicated on the work of these famous computer scientists in 1968, keep that history in mind. You're emulating a slightly cranky letter to the editor. It's frighteningly common-- there are now 28,800 web pages with the exact phrase "considered harmful" in the title.

This leads, perhaps inevitably, to Eric Meyer's "Considered Harmful" Essays Considered Harmful. He points out that choosing this style of dialogue is ultimately counterproductive:

There are three primary ways in which "Considered Harmful" essays cause harm.

  1. The writing of a "considered harmful" essay often serves to inflame whatever debate is in progress, and thus makes it that much harder for a solution to be found through any means. Those who support the view that the essay attacks are more likely to dig in and defend their views by any means necessary, and are less receptive to reasoned debate. By pushing the opposing views further apart, it becomes more likely that the essay will cause a permanent break between opposing views rather than contribute to a resolution of the debate.

  2. "Considered harmful" essays are most harmful to their own causes. The publication of a "considered harmful" essay has a strong tendency to alienate neutral parties, thus weakening support for the point of view the essay puts forth. A sufficiently dogmatic "considered harmful" essay can end a debate in favor of the viewpoint the essay considers harmful.

  3. They've become boring clichés. Nobody really wants to read "considered harmful" essays any more, because we've seen them a thousand times before and didn't really learn anything from them, since we were too busy being annoyed to really listen to the arguments presented.

If you have a point to make, by all means, write a great persuasive essay. If you want to maximize the effectiveness of your criticisms, however, you'll leave "considered harmful" out of your writing. The "considered harmful" technique may have worked for Wirth and Dijkstra, but unless you're planning to become a world famous computer scientist like those guys, I'd suggest leaving it back in 1968 where it belongs.

[advertisement] Axosoft OnTime 2007 is a bug tracker that manages requirements, tasks, and help desk incidents. It's designed to help teams ship software on time. Available for Windows, Web, and integrated with VS.NET 2005. Installed or hosted. Free single-user license.

Posted by Jeff Atwood    View blog reactions

 

« Hardware Assisted Brute Force Attacks: Still For Dummies How To Achieve Ultimate Blog Success In One Easy Step »

 

Comments

The Language Log website is interesting -- thanks for the link!

transcriber on October 25, 2007 04:39 PM

Someone should tell the Codebetter.com folks about writing persuasive articles instead of insulting everybody that's not part of their cult.

foobar on October 25, 2007 04:44 PM

http://catb.org/jargon/html/C/considered-harmful.html
--
Amusingly, the ACM considered the resulting acrimony [from publishing "GOTO Considered Harmful"] sufficiently harmful that it will (by policy) no longer print an article taking so assertive a position against a coding practice.
--

Jeff Atwood on October 25, 2007 05:00 PM

> What is an early Return, or an early Exit For other than
> a tightly scoped GOTO?

Exactly. Which is why I try to avoid them, too.

Peter on October 25, 2007 05:38 PM

Yeah, but that's still nothing compared to the time some guy went topless at ACM SIGGRAPH: http://www.siggraph.org/programs/archive/reports/conference/2005/articles/papers/fast-forward-paper-session

Two years later the organizers were still traumatized.

D. Lorentz on October 25, 2007 06:10 PM

Goto is alive and well in C#.

I've seen this in a current code base:

(psuedocode)
clptryagain:

try
{
//Do something
}
catch
{
retrycount++;
if (retrycount <= maxretries)
{
goto clptryagain;
}
}

I thought I buried goto for good in VB6 code but apparently it exists in C# as well. The horror, the horror...

Does anyone know why it was included in C#?

Also, check this out:

A goto statement is executed as follows:
2 If the goto statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. 3 When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. 4 This process is repeated until the finally blocks of all intervening try statements have been executed.
5 Control is transferred to the target of the goto statement.

Also I found this GEM on MSDN:

http://msdn2.microsoft.com/en-us/library/13940fs2(VS.80).aspx

// statements_goto.cs
// Nested search loops
using System;
public class GotoTest1
{
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];

// Initialize the array:
for (int i = 0; i < x; i++)

for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();

// Read input:
Console.Write("Enter the number to search for: ");

// Input a string:
string myNumber = Console.ReadLine();

// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}

Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;

Found:
Console.WriteLine("The number {0} is found.", myNumber);

Finish:
Console.WriteLine("End of search.");
}
}

Jon Raynor

Jon Raynor on October 25, 2007 06:19 PM

I'm fairly certain though that adding "considered harmful" to any post on programming.reddit.com guarantees at least 30% more votes.

engtech on October 25, 2007 06:23 PM

I've often pondered writing an "oxygen considered harmful" article filled with accurate and not misleading facts, just to see who would try to suffocate themselves and who would attempt to breath pure oxygen just to prove that they don't think its harmful.

Bob on October 25, 2007 06:56 PM

@Jon:

Because if you really, really, really know what you're doing, and you really, really, really need the performance boost that GOTO can sometimes provide (http://kerneltrap.org/node/553/2131), it's good to have in the language. That being said, I never use it. Maybe it should generate a low-level compiler warning, and you should have to disable it with a compiler switch or a #pragma-type thing...


David Markle on October 25, 2007 07:06 PM

I prefer this comic:
http://imgs.xkcd.com/comics/goto.png

Jeff on October 25, 2007 08:00 PM

Jon Raynor,

Just like most instruction languages, MSIL fundamentally only has "goto" (aka "jump") as it's branch enactment. An "if" is re-phrased as "jump if" or (more commonly) "jump if not". Do/while are re-phrased as "if" with appropriate loop control logic inserted. "switch" is re-phrased as either a series of "if...else" (most common) or an offset address jump table.

You only need to see how often "goto" turns up in decompiled MSIL code to realise that if a decompiler can't tell the difference, there probably isn't a difference.

"goto" was included for completeness, being the fundamental building block from which all other loop controls can be functionally constructed, to leave it out, is to make the statement "we are smarter than you". No development team, no matter how high-profile, wants to make that statement (except Java).

Meanwhile, "goto considered harmful" should really be understood as "a high ratio of goto compared with lines-of-code is considered harmful (because readability drops off rapidly)".

Jeff Atwood,

I'd be interested to hear your comparison of "goto" versus "exceptions". I find it an interesting comparison myself and I'm still undecided if either should be labelled inherently evil.

Most people who praise the idea of exceptions; spit on goto.

But what is an exception if not a much more complicated, non-local, stack-linear version of a goto?

Of course there are numerous differences, but which ones are good?
* A goto is local, you can't jump out of the current stack-frame - an exception can jump to any point on the existing stack; worse, the stack will be unwound as it goes and this very act may trigger an exception that exceeds your catch clause level and jumps elsewhere.
* A goto translates to a single intruction, it's effects are easy to predict and even easier to emit in code. An exception generates an indeterminate number of instructions, it's difficult to say, especially where a GC is involved, what will happen - even the compiler (or the VM in the case of C#) often takes considerable time to figure out what to do.
* A goto states explicitly where the next instruction will execute. An exception? Who knows! Are there objects to be destroyed? Is there another catch clause you didn't see in your human-frailed browse of the stack-frame? Is there a library callback inbetween the exception and your catch that might silently drop it and resume?

Go on Jeff, "exceptions versus goto". You know you want to.

Andrew R on October 25, 2007 08:12 PM

I think Strunk & White summarized it as "cliches in writing considered harmful" :)

Scott on October 25, 2007 08:15 PM

GOTO(arrow symbol) is more natural than if/then/else when I draw flow chart before writing code.
So I think GOTO is more useful in graphical environment than text environment.

jack on October 25, 2007 08:47 PM

It's almost impossible for most of the programmers alive today to understand the world as it was when Dijkstra wrote that paper.

In 1968 the vast majority of source code was on PUNCHED CARDs (or punched card images stored on some media). Indenting or unindenting a paragraph required repunching all of the cards for each of the lines being shifted!

Changing the logic with a GOTO might involve just punching one card, and could be done in an hour or less. But reformatting a large chunk to not use the GOTO might really take days! (Write out the entire code section again on special coding pads that got sent to the keypunchers; wait for the punch cards to come back; proof-read all of them very carefully; submit a deck to insert the new, revised code into the PANVALET source data base; wait for that job to come back; submit another deck to compile-link-and-test overnight; etc., etc.)

So naturally, the more any given program or subroutine had been maintained, the more GOTOs and "spagetti logic" it acquired, until it was virtually unreadable
and unmaintainable.

It's undoubtably true that programmers used more GOTOs before Dijkstra and fewer of them in the years that followed. And it's certain that code quality (correctness and maintainability) improved along with that. However, I submit that it would be impossible to tell how much of that was due to the Dijkstra paper, versus how much of that was due to the introduction of time-sharing terminals that allowed programmers to edit thier source electronically in real time.

Jim Conyngham on October 25, 2007 08:53 PM

One of the patterns I use to avoid ugly GOTOs is the do {...} while (0); loop

For some strange reason, my colleages all seem to think that this structure looks weird.

Example psuedocode:


do {
open__input_file();
if (failed)
break;

allocate_buffer();
if (failed)
break;

open_output_file();
if (failed)
break;

read_input_data ();
if (failed);
break;

... etc.
} while (0);

Jim Conyngham on October 25, 2007 09:00 PM

Exceptions and GOTOs are very different things. Exceptions should be used for exceptional situations that you don't want to deal with in the standard program flow, GOTOs are a sloppy way of writing the standrad program flow.
Yes, there's people that uses exceptions for non-exceptional situations and that is bad (and very inefficient). But this doesn't make GOTOs better, using GOTOs stays wrong, using Exceptions as a substituite for GOTOs is twice wrong:
1. because you are misusing exceptions
2. because you are using GOTOs.

E[X] on October 25, 2007 11:26 PM

> I've often pondered writing an "oxygen considered harmful" article filled with accurate and not misleading facts

Ah yes, reminds me of the perils of Dihydrogen Monoxide..

http://www.liveleak.com/view?i=3a9_1175530605

From the excellent and highly recommended Penn & Teller series "Bullshit".

http://en.wikipedia.org/wiki/Bullshit!

Jeff Atwood on October 25, 2007 11:50 PM

The main point of Dijkstra was that with a goto in the code, you can't proof mathematically that the code is correct. That's still true today in OO languages.

Frans Bouma on October 26, 2007 01:14 AM

* A goto is local - Not in the languages Dijkstra was talking about that is why it was potentially so bad to use them

The whole point of the paper was to show that the easy solution (goto's) were a bad idea in the long run since the code was unmaintainable, and many programmers of the day used them in non-standard ways ... what happens if you jump into a for loop ...

A goto used properly as an optimisation in a clearly defined manner as an alternative to an exception or similar can be good but in most other cases it is a kludge where another statement would be better, clearer, and easier to maintain

The main thrust behind "Goto considered harmful" considered harmful is that yes goto's are mostly bad but if people are put off *ever* using them then they can write less clear code simply to avoid using them

Jaster on October 26, 2007 01:32 AM

The only time I see goto statements are in open source code.....I know what that tells me!

Jim on October 26, 2007 01:42 AM

@Jim Conyngham, that is even worse than I thought. Young naïf that I am, I was simply imagining BASIC and C with loads of GOTOs being hacked in rather than doing what might be called refactoring now. And of course Wirth would have been pleased to show his own languages in a good light. It is all to easy to forget that the world was so different before MS and Borland started making their IDEs with a single keystroke to compile, link _and_ build. Your do...while pattern is very perlish.

John Ferguson on October 26, 2007 01:52 AM

GOTO is not a performance improvement. If it is the only way to improve the performance of your program then something went wrong around the design phase.

smsorin on October 26, 2007 01:56 AM

A few years ago I found a paper titled "Gotos Considered Harmful and Other Programmers' Taboos", from a Workshop of the "Psychology of Programming Interest Group". You can find it at http://www.ppig.org/papers/12th-marshall.pdf.

Avoiding a goto when it is the correct option - by using Jim Conyngham's do/while/break technique - is a very bad idea. It seriously harms readability because the programmer EXPECTS that the loop will be taken at least once with some set of inputs. Targeted local gotos, as present in all modern languages in preference to line-numbered global gotos, are clear enough to understand. I would generally restrict gotos to FORWARD jumps only, a backward jump is a loop and should be coded as one.

The overloaded use of 'break' in C-based languages - to indicate the end of a case in a switch statement, and to break out of a loop - may require you to use a goto if you need to break out of a loop when you're in a switch statement in a loop. One solution is of course to put the switch statement into a separate function.

You'll use goto rarely - maybe a few times a year, in most cases. If you're using it in C++ to jump to common cleanup routines, your time might be better invested in making automatic cleanup, via stack local objects' destructors, work properly. In C#, you should be looking at IDisposable and using blocks. But goto is a handy tool to have, if used judiciously and sparingly.

Mike Dimmick on October 26, 2007 02:23 AM

>it's only a minor hazard compared to the COMEFROM statement,
>but I'm glad to have both of those largely behind us

COMEFROM is alive and well, and very widely used. The only change made was that the marketing guys rebranded it as 'exception handling'.

Dave on October 26, 2007 02:26 AM

In the Jurassic era when I helped students debug their programs, one guy had a program where all the variables were girls' names. He also deliberately introduced a slight inefficiency into his program, with the statement: goto bed;

One of my father's colleagues, with a lower level of creativity, had this in a program: goto hell;

As for me and creativity, well, I got 0.

None on October 26, 2007 02:34 AM

I don't really agree with the idea of returning early from functions. As Jeff says it is just a tightly scoped GOTO and I think it can adversely affect readability.

In fact our in-house coding standard explicitly recommends against it.
Multiple return point in the same function makes it harder to understand and goes against the "don't make me think" principle".

Generally the only reason I would use early return is for basic pre-condition sanity checking at the start of a function.

e.g.

char* some_function( char* somestring, int somenumber )
{
// Sanity checks
if ( somestring == NULL ) return NULL;
if ( somenumber <= 0 || somenumber < LIMIT ) return NULL;

// Do real work..
}

And even there I would consider exceptions instead, if they were available.

Similarly I think breaking out of loops is overused.
Why not just add a boolean exit condition to the loop?
It makes the intent clearer and means there are less paths to consider.

e.g. if I write

for ( int i = 0; i < LIMIT && !found_thing; i++ )

then you know just by reading that line that I am traversing through i until I hit a limit or find the thing I am looking for. Using break would mean the exit condition was less clear.

Graham Stewart on October 26, 2007 03:14 AM

I've seen goto in case statements in C# to get round the "can't fall through" compiler error when you have something in a case.

This becomes another religious issue in the end. Sure, more people are on the same side of the fence over the whole GOTO thing (me included), but where d'you draw the line? People will argue ceaselessly that VB isn't a proper programming language, others will say that you shouldn't have single-line if statements like this:

if (!ValidateInput()) return;

In these examples it's less clear who's right or wrong. In this particular example my opinion differs from that of a colleague of mine, where he doesn't like it but I think there are two situations where it's okay (the one above, and when you're disposing objects in finally blocks). Neither of us is right or wrong, we just have preferences. In the case of GOTO, much as I dislike seeing it, the only reason we think it's "wrong" is because enough people think it is.

Neil Barnwell on October 26, 2007 03:56 AM

Neil: yes, C# has a sub-type of goto with restricted scope, "goto case", which is particularly for declaring fall-throughs in switch statements.

Although this uses the dreaded cursed word, it is not a "real goto" and it is considerably less evil than the implicit fall-through used in C/C++

Graham Stewart on October 26, 2007 06:47 AM

For the people who think GOTO is so incredibly horrible that it shouldn't even be in a language, I would suggest that you read something from some dude named "Donald Knuth" who had something to say on the subject.

http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf

Peter Crabtree on October 26, 2007 07:18 AM

I use it from time to time, I'm just that crazy ... but I always have a safety variable to make sure I don't lock up ;-)

tm on October 26, 2007 07:51 AM

The "go to" discussion: old news
The "Considered harmful" discussion: boring

james maida on October 26, 2007 08:36 AM

The most common use I have for a goto is in image processing where I am usually using two loops and I need a double break. It really can make code more readable.

for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (image[x][y] == 0)
goto found;
found:

Compared to this

for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
if (image[x][y] == 0)
break;
if (x < w)
break;
}

or this

for (y = 0; (y < h) && (image[x][y] != 0); y++)
for (x = 0; (x < w) && (image[x][y] != 0); x++)
{}

In the first case there is only one place where I check if I'm done, in the other two there are two places, thus they have added complexity.

mccoyn on October 26, 2007 10:40 AM

mccoyn: But couldn't you just write that as:

for (y = 0; y < h && !found; y++)
for (x = 0; x < w && !found; x++)
found = (image[x][y] == 0);

Graham Stewart on October 26, 2007 10:56 AM

(By the way Jeff, it would be really handy to have some kind of PRE or CODE tag available to us when posting code snippets!)

Graham Stewart on October 26, 2007 10:58 AM

Graham:

You are still writing two tests, just caching the result (and fixing my bug).

mccoyn on October 26, 2007 11:46 AM

In the 80s I saw an article in a mainframer magazine that started off saying all logic can be expressed by sequence, alternation and iteration. From this he concluded that COBOL "perform" was "harmful" and showed how to simulate the three major structures with GOTO. For example, don't use perform while, use GOTO the top of the loop. With no subroutines, his outermost structures were the length of the program. (I was reminded of this the other day when I opened a Java class with one 5,000 line method.)

I've never seriously missed GOTO in Java.

Jim on October 26, 2007 12:25 PM

I hate goto's for the simple reason that people who shouldn't be programming in the first place see them and think they're a perfect hammer. Then they start seeing everything else as nails.

I've debugged plenty of production code with goto's all over the place, and then the original programmers sit there wondering why it doesn't work right.

Greg on October 26, 2007 02:42 PM

Your essay (and Earth) - mostly harmless.

Mark H on October 26, 2007 08:11 PM

I did not think you had many FORTRAN or BASIC programmers reading your blog . . .

David Ginger on October 27, 2007 05:51 AM

You can still make a case for GOSUB for that matter in languages with only two levels of procedure scope.

Some procedure that needs to use the same sequence of code operating on a hefty collection of local data items more than once. It isn't worth the overhead of making an out-of-scope procedure and passing a raft of parameters to it.

hmm on October 27, 2007 10:47 AM

It seems like there is a new modern trend in essays. Which I would call "is dead" :-) Remember, "Computer science is dead?" "Microsoft is dead?" Who's next? :-)

voivoi on October 27, 2007 04:12 PM

Graham Stewart,

C#:

switch( k )
{
case 3:
System.Diagnostics.Debug.Print( "case 3" );
goto case 6;
case 6:
System.Diagnostics.Debug.Print( "case 6" );
break;
}

compiled IL result:

L_000f: ldstr "case 3"
L_0014: call void [System]System.Diagnostics.Debug::Print(string)
L_0019: nop
L_001a: br.s L_001c
L_001c: ldstr "case 6"
L_0021: call void [System]System.Diagnostics.Debug::Print(string)
L_0026: nop
L_0027: br.s L_0029

I draw your attention notably to the 2 "br.s" instructions, each of which is an unconditional jump (goto) to the VERY NEXT instruction (fall-through). Both occurences are superfluous; the code does not change meaning AT ALL when these instructions are replaced with "nop".

And you conclude that C/C++ is the evil version?

Which of the following 2 conditions does your user most care about:
* A program that is responsive, or
* A program whose source code is "pretty"

You can argue the merits of beautiful code all day, but be careful not to lose sight of the user; THEY are your ultimate critic.

Andrew R on October 28, 2007 07:34 PM

Multiple returns rules! Guard clauses, dispatch methods... I love it!

As soon as you're using conditionals (which, granted, [http://catpad.net/michael/apl/ isn't always the case]) multiple returns will probably be useful.

Death to the cargo cultish idiom of
int some_function(boolean val) {
int result = 0;
if (val) result = 3; else result = 4;
return result;
}

Sunnan on October 29, 2007 12:56 AM

Jim: "I've never seriously missed GOTO in Java."

I do right now, writing a little code generator. As it seems I need to rely on javac doing some heavy common tail combination. Missing the comma operator, too.

Andreas Krey on October 29, 2007 01:32 AM

Wirth is just awesome. That's all I can say :-)

LKM on October 29, 2007 08:33 AM

mccoyn:

Agreed, I am still testing twice. But if the goal is to improve code readability (which was your stated reason for using GOTO) then I find my approach more readable and maintainable. The 'for' line clearly states the possible exit conditions, rather than burying them in the body of the loop.

Andrew R:

My focus IS the user and I'd be prepared to bet that the user would rather have a (marginally) slower program with fewer bugs.

You're right of course, the IL output isn't very clever there. But that is a limitation of a dumb compiler that isn't doing a very good job of optimising. It is not a fault of the language construct itself.

And realistically, how many picoseconds do these "superfluous" breaks add?
I can't see their inclusion altering the responsiveness of a program in any significant way. If my application was that time-critical then I wouldn't be using managed code in the first place.

The reason I said that the C/C++ approach to switch is evil, is that it defaults to falling through and 99% of the time when I write a switch case, I don't want it to fall-through.
Therefore omitting a break and allowing fall-through would be a bug in 99% of the switch cases I write. In other words, it defaults to a bug.

(This is something Jeff touched on in his post called "Falling into the Pit of Success" http://www.codinghorror.com/blog/archives/000940.html )

On the rare occasion that I do want to fall-through, then I have to add a comment indicating that I have deliberately omitted break, otherwise a future maintenance programmer is likely to "correct" it.

C# on the other hand, prevents you from falling-through without explicitly declaring your intent to do so. It defaults to preventing a bug.

Furthermore it enhances maintainability by allowing each switch-case to be self-contained. You can introduce new cases and re-order the existing ones without breaking anything (try that when you are using fall-through code in C).

The C# approach also simplifies more complex cases where there are multiple fall-throughs. Like this:

switch ( flavour )
{
case PearApple:
System.Diagnostics.Debug.Print( "Pear And " );
goto case Apple;

case OrangeApple:
System.Diagnostics.Debug.Print( "Orange And " );
goto case Apple;

case Apple:
System.Diagnostics.Debug.Print( "Apple" );
break;
}

Graham Stewart on October 29, 2007 08:49 AM

> Someone should tell the Codebetter.com folks about writing persuasive articles instead of insulting everybody that's not part of their cult.

> foobar on October 25, 2007 04:44 PM

As a current member of Codebetter I sympathize with your view. Take heart that the entire staff should not be painted with that brush and that several of us are launching a new blog site without the vitriol soon.

I sincerely hope that the community will have an open mind and realize that the views of one are not the views of all.

Eric Wise on October 29, 2007 10:40 AM

Can I point out for the umpteenth time, the actual statement was "Non-local gotos considered harmful!" Think setjmp(), longjmp(). Why discuss using a goto to simulate standard control structures? That was not the point of the article.

Terrier on October 29, 2007 12:38 PM

Terrier:

The text of the Dijkstra article is linked to by Jeff at the start of his post.
If you want a more authoritative source then the original article is available in the ACM archives at http://doi.acm.org/10.1145/362929.362947

It is entitled "go to statement considered harmful", no mention of "non-local" there.

Although Dijkstra does discuss the problems with using goto in the new and crazy world of procedures, he also mentions the problems with using goto in "repetition clauses (like, while B repeat A or repeat A until B)".

Also the discussions above are not about "using a goto to simulate standard control structures", they are about whether it is ever valid to use goto to short-circuit such structures.

Graham Stewart on October 30, 2007 05:54 AM

>> Also the discussions above are not about "using a goto to simulate standard control structures", they are about whether it is ever valid to use goto to short-circuit such structures.

Well put Graham.

Gotos are a low level building block. When you can use a higher level control structure it will be more easily understood and you should do it. When none of the control structures fit your needs you must roll your own and goto allows this in the simplest possible way.

mccoyn on October 30, 2007 08:02 AM

Did you mean 1986 or really 1968? Seems a little strange that the response to the original article would take so long to appear...and did they even have goto statements in '68?

David Mackey on October 30, 2007 07:22 PM

Why not try Haskell and get pure, statically-checked, _first class_ GOTO statements by way of continuations? They're also frightfully hard to understand which works as a nice kind of low-pass filter: if you're a good enough programmer to understand them, you're probably good enough to use them appropriately, too.

David House on October 31, 2007 05:14 AM

David: yes Dijkstra's original letter was published in March 1968.
The letter is seen by many as the beginnings of structured programming.

And yes, they did have GOTO in 1968!
In fact the point was that they didn't much else when it came to controlling the flow of the program.
Even such basics as iterative loops were typically implemented using GOTO.

Graham Stewart on October 31, 2007 05:24 AM

> if you're a good enough programmer to understand them, you're probably good enough to use them appropriately, too.

And what about the lowly maintenance programmer who picks up your code in two years time?
Making his job easier should be more important than writing "clever" code.

Graham Stewart on October 31, 2007 05:55 AM

Though the 1949 example is cute, the use of "considered harmful" in the headline of a major newspaper is pretty rare. My search on the historical New York Times, Wall Street Journal, Chicago Defender, Los Angeles Times, and Washington Post (via ProQuest Historical Newspapers) turns a mere EIGHT headlines with the words "considered harmful" in them from the 19th through the 20th centuries.

Of those, only the 1949 is a pure case of "X considered harmful" without anything else. Here are the headlines:

DOOM OF TYPHOID.; Discovery Made at Washington. Large Bodies of Water Can be Readily Sterilized by Solution of Copper. Cholera Bacteria May be Exterminated as Well in Three Hours Time. Preparation Not Considered Harmful to Man or Beast Incidental Agent.
Los Angeles Times (1886-Current. May 9, 1904. p. 1

PENDING RAILWAY BILLS NOT CONSIDERED HARMFUL; Corporation Lawyer Says Elimination of Stock and Bond Feature and Other Changes Remove Radical Features--Security Supervision.
Wall Street Journal (1889-Current file). New York, N.Y.: May 25, 1910. p. 2

Letters to The Times; Pump-Priming' Is Upheld Under Present Conditions, Second Try Might Be Successful Basis of the Theory Unintegrated Policies Broadening Citizenship Oath Quebec's Civil Code Sources Evil Seen in Monopolies They Are Considered Harmful Both to Production and Distribution Financing the Retailer Quarantine Move Opposed New Traffic System Wanted DOGWOOD
New York Times. Apr 22, 1938. p. 18

Single Tax Seen Danger; Resolutions Oppose Measures Considered Harmful to Realty
Los Angeles Times (1886-Current File). Los Angeles, Calif.: Oct 30, 1938. p. E2

Rent Control Controversy; Enacting Now of Hasty Legislation Considered Harmful
ROBERT S. FOUGNER.. New York Times (1857-Current file). New York, N.Y.: Aug 19, 1949. p. 16

CONSIDERED HARMFUL; Palm Springs Schools to Outlaw Sororities
Los Angeles Times (1886-Current File). Los Angeles, Calif.: Apr 15, 1960. p. A7

Experts Call for Balance In Helping Young Cope; Dwelling on Negatives Considered Harmful
The Washington Post (1974-Current file). Washington, D.C.: Jan 31, 1986. p. A12

Physicians, in Film, Decry Embargo's Effect on Iraqi Children; The shortage of medical supplies is considered harmful to innocent victims. A Stony Brook doctor, a priest and a controversial documentary.
By MARJORIE KAUFMAN. New York Times (1857-Current file). New York, N.Y.: Dec 27, 1992. p. LI10


I know, you were really curious, right? :-)

Shmork on October 31, 2007 08:06 AM







(hear it spoken)


(no HTML)




Content (c) 2008 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.