GOTO considered harmful. Except for…

By

December 27, 2014General8 Comments

The goto is considered harmful. In general. If anyone finds a goto keyword somewhere in a code base nowadays, the default action is to identify the author of this code line and instantly assassinate him. It’s safe, because jury always sides with heroes who do good for public.

Java doesn’t even have this keyword, probably in a bid to maximize life expectancy for Java developers.

But you know, software development is not only Java. Someone still uses C, there are a lot of fellas doing C++ out there, and they still have possibility to compile code with plenty gotos in it. Damn, even C# has goto keyword. And because C# is younger than Java, it is supposed to learn from Java mistakes and be more evolved, at least in a sense of language syntax.

Yet C# has goto.

 

Explanation in MSDN is naïve. It says goto might be useful for a) control switch statements or b) exiting deeply nested loops. Both statements don’t hold water, because:

  1. Thou shalt not reuse code by jumping up and down the switch case blocks with goto’s. It’s just incredible dangerous. Use procedures! People have used procedures since 1950ies, it’s a classic technique. Or use fallthroughs. Fallthroughs are cool too.
  2. Thou shalt not exit loops with goto. Use return instead!

The high-performance code where function call overhead is a problem inevitably gravitates towards unsafe code. If C# language designers included goto for addressing high-performance problems only, they would have limited this keyword for usage in explicitly unsafe code blocks only (you know, the blocks where you can use pointers).

So in short: exiting deeply nested loops should NOT happen with goto. Code reuse within switch statements should NOT happen with goto either. I’m sorry C# developers, the C# language designers have sinned. Jury is on your side.

 

 

…Where is goto applicable then?

 

 

The only justifiable usage for goto statement I’ve ever seen was in a modern ANSI C code. It was where a procedure made a lot of critical resource allocations first, and had to perform cleanup for each resource before exiting.

  • Because C hasn’t got finally clause, you cannot use return + finally as you could in Java or C#.
  • Because C has no exceptions mechanism, each error checking is done manually – by verifying return codes.
  • Because C has no object-oriented stuff (like objects, constructors and destructors), you cannot use Scope-based Resouce Management.

Here’s the code without goto:

int whatever(…){
    int resource1 = acquireResource1();
    if (resource1<0)
        return ERROR;

    int resource2 = acquireResource2(resource1);
    if (resource2<0){
        cleanupResource1(resource1);
        return ERROR;
    }

    int resource15 = aqcuireResource15();
    if (resource15<0){
        cleanupResource14(resource14);
        …
        cleanupResource2(resource2);
        cleanupResource1(resource1);
        return ERROR;
    }

    // now for the business logic
     …
    int result = invokeSomething(resource1, resource 12);
    if (result<0)
          // jump to resource cleanup
    …

    // cleanup logic
    if (resource15)
         cleanupResource15(resource15);
     ….
    if (resource2)
        cleanupResource2(resource2);

    if (resource1)
         cleanupResource1(resource1);
}

 

Clearly, this code violates DRY (identical code for resource cleanup before the business logic and after it).

 

Could we do have the same functionality without duplicated code AND without goto? Sure! Many ways possible. But all are ugly and extremely verbose. Usage of goto in this scenario is okay. Thou shalt not kill software developers who code in C and use goto for this particular case only.

 

A takeaway here? Goto considered harmful. Period. Small asterisk: unless you use C and have to deal with a lot of resource cleanups and don’t want your code duplicated all over the place.

 

8 Responses to “GOTO considered harmful. Except for…”
  1. Jev

    Hi,

    Firstly, as I remember (correct me if I am wrong) Java has labeled breaks, which basically the same as goto in C#. What C# did is just chose good name for these labels.

    Another point is that switch “fall through” is illegal in C#, so you cannot use

    switch (a)
    {
    case 3:
    b = 7;
    case 4:
    c = 3;
    break;
    default:
    b = 2;
    c = 4;
    break;
    }

    But you can use goto instead.

    switch (a)
    {
    case 3:
    b = 7;
    goto case 4;
    case 4:
    c = 3;
    break;
    default:
    b = 2;
    c = 4;
    break;
    }

    Does it sound reasonable?

  2. gugit

    Oh my god… C# language designers are really solving the well-known technique called “fallthrough” with evil goto?

    • Jev

      Historically switch “fall-through” is one of the major source of bugs, so C# language designers decided to forbid it to avoid accidental fall-through. If you want it, then say it explicitly using got statement.

      But all in all, it’s the same as arguing about whether or not curly braces should be aligned in columns or ‘tabs versus spaces’ debates. IMHO in same cases gotos can lead to more readable and simplistic codebase.

      Some references:

      In some cases, gotos can result in faster and smaller code. Knuth’s marvelous 1974 article cited a few cases in which gotos produce a legitimate gain (Knuth 1974).

      Good programming doesn’t mean eliminating gotos. Methodical decomposition, refinement, and selection of control structures automatically leads to goto-free programs in most cases. gotolessness is not the aim, but the outcome, and putting the focus on no gotos isn’t helpful (Code complete, Steve McConnel)

      • gugit

        “gotolessness is not the aim, but the outcome, and putting the focus on no gotos isn’t helpful.”

        Steve McConnel shot a good one here. I like how it sounds. Substitute “goto” with “code smell” (or just about any code smell out there) and you get nice strong controversial expert opinion!

        “Absence of god objects is not the aim, but the outcome, and putting the focus on no god objects isn’t helpfull.”

        “Absence of code smells is not the aim, but the outcome, and putting the focus on no code smells isn’t helpfull”.

        “Absence of world’s worst practices is not the aim, but the outcome, and putting the focus on eliminating world’s worst practices isn’t helpfull”.

        B-)

  3. https://wiseintro.co/

    Definitely consider that which you said. Your favorite reason appeared to be
    on the internet the easiest thing to take into accout of.

    I say to you, I certainly get annoyed whilst folks consider concerns that they plainly don’t recognize about.
    You managed to hit the nail upon the top and also
    outlined out the whole thing with no need side-effects , other people could take a signal.

    Will probably be again to get more. Thanks

  4. Wilford Liversidge

    Need to find effective advertising that isn’t full of BS? Sorry to bug you on your contact form but actually that was kinda the point. We can send your advertising copy to websites through their contact forms just like you’re reading this ad right now. You can specify targets by keyword or just go with bulk blasts to sites in the country of your choice. So let’s say you want to push through a message to all the interior decorators in the US, we’ll scrape websites for only those and post your advertisement to them. As long as you’re promoting something that’s relevant to that type of business then you’ll get awesome results!

    Send a quick note to muhammad2435tay@gmail.com to get info and prices

  5. Sprinklerttk

    удалите,пожалуйста! .

  6. John

    Unquestionably consider what you said. Your #1 explanation gave off an impression of being

    on the web the simplest thing to take into account of.

    I say to you, I unquestionably get irritated while people consider worries that they clearly don’t perceive.

    You figured out how to hit the nail upon the top and furthermore

    illustrated out the entire thing with no need for results, others could take a sign. Thanks

Leave a Reply