“GOTO Death & Slaughter”


We recently had an internal discussion concerning the use of GOTO’s in code and its
implications. I was reminded of a great paper by Djikstra on the subject… it’s a
quick and great read: http://www.acm.org/classics/oct95/.

For those of you who consider the title of this posting slightly
odd, please keep in mind that I’ve now seen Pirates of Penzance 4 times in the past
few weeks. Fantastic show!

Comments (3)

  1. gerrard says:

    I feel slightly guilty even when I throw too many exceptions. I sometime write code like:

    if (somethingBad)

    throw new ApplicationException("Something bad.");

    else

    {

    //do something

    }

    to make it clearer that there’s a program flow change, but I’ve developed a bad habit of writing stuff like:

    if (somethingBad)

    throw new ApplicationException("Something bad.");

    //do something

    What are your thoughts on minimizing the impact of Exception handling on the ability to easily interpret code flow?

  2. Steve says:

    I don’t think there’s a major difference between the two examples you’ve posted, mainly because of their simplicity (one if statement resulting in possibly throwing one exception). Personally, in most situations where this arises I prefer the latter as it is easier to read and does the exact same thing; in fact, the MSIL generated for each by the C# compiler will be exactly the same.

    Guard statements are often used as in the latter case to handle parameter checking in functions. This makes it clean to write code like:

    if (param1 == null) throw new ArgumentNullException("param1");

    if (param2 == null) throw new ArgumentNullException("param2");

    if (param3 == null) throw new ArgumentNullException("param3");

    // now do work of method

    I’d find it annoying to read that same code written as:

    if (param1 == null)

    {

    throw new ArgumentNullException("param1");

    }

    else

    {

    if (param2 == null)

    {

    throw new ArgumentNullException("param2");

    }

    else

    {

    if (param3 == null)

    {

    throw new ArgumentNullException("param3");

    }

    else

    {

    // now do work of method

    }

    }

    I think the guard statements make the code flow much easier to understand.