Wednesday, June 1, 2011

Why I've started using goto's...

So every since I can remember, people have said the using goto's is a Bad Design decision and I've always agreed. There is no situation where one _must_ use a goto. And here is my evolution from using goto's as a beginner, to shunning them to eventually starting to use them again.

1982-1983 our family gets our first computer, an Apple ][+ . I am 6 or 7 years old and learn how to write a simple game in AppleSOFT BASIC. I use GOTO's all over the place.

1989-1990 I have begun to learn 6502/65816 assembly language for the Apple ][gs. Since it's assembly language using absolute branches and jumps (ie GOTOs) is typical and acceptable.

1991 I go on a vacation to Switzerland for 1 month. For some reason, while I was there, I read my first book on the C language. At this point I start shunning GOTO's.

1993 I start taking a few classes at the University of Utah. The instructor sternly tells us to never use goto statements.

1997 I take a class on computer programming that emphasizes good coding practices. One of them is to only include one return statement per function. I embrace this concept and realize that I can do pretty much anything I want by declaring a variable containing the result code at the beginning of all functions, then get through the function using nested if/else/while/for conditional sections.

1999 Development on DAPHNE begins.

2003 I finally graduate with a BS in computer science

2007 I am beginning to get really weary of nested if/else/while/for conditional sections. It's ok for small stuff but a maintenance nightmare when the nesting gets complex. I realize that using exceptions (try/catch) to abort functions early is the way I can stop the nesting madness. Instead of saying "if (something succeeds) { }" I say "if (something fails) throw exception". This seems to solve my problem... or does it?

2009 A co-worker casually mentions that using GOTO's can be useful

2010 Some of the embedded platforms I want to work on do not support (Android) do not support try/catch exceptions in C++. Try/catch generally is expensive and only useful on desktops where CPU power and memory is plentiful. At least for now.

2011 I start using goto statements as a primitive form of try/catch. Instead of throwing an exception on error, I just goto the end of the function. This allows me to still only have one return statement per function while also avoiding nasty if/else nesting.

So there you have it. I'm not proud of using goto's.. in fact, if someone can find a solution that meets my goals without goto's, I'd love to hear it.

No comments:

Post a Comment