Re: break, continue, goto
Re: break, continue, goto
- Subject: Re: break, continue, goto
- From: "M. Uli Kusterer" <email@hidden>
- Date: Mon, 4 Aug 2003 17:06:49 +0200
At 19:18 Uhr +1000 04.08.2003, David Thorp wrote:
In my (limited) programming experience (with such things as basic
and pascal many years ago) I learned that spaghetti code is bad and
thus getting out of loops and conditional statements using things
like continue and break (except for the switch statement) and using
goto at any time, are all examples of bad programming, where one
should carefully choose one's exit conditions and conditional
statements very carefully instead.
As it always is in life, you shouldn't take such rules in programming
to be absolutes. There are numerous occasions where break, continue
and even goto are perfectly good (in C). In C++, it would be another
issue entirely, because there they've added constructs to avoid these
problems. But this is Cocoa-Dev after all...
It might be better to label them as "dangerous" commands. It is a lot
easier to introduce subtle bugs, like memory leaks, into your
application with goto, break and continue, for example by jumping
over a "free" statement. Since "if", which is usually used instead,
uses block brackets to enclose several statements, such bugs are
usually much more obvious there than with the almost invisible
"goto". Another programmer fixing something in your code may not even
notice he just wrote code that will not be executed due to a "goto"
in half the cases...
As a rule of thumb, always look for other, more "high-level" commands
that can do what you're doing with "goto". C++ and ObjC offer
exceptions for error handling, loops and if-statements for branching.
You should very rarely, if ever, need a "goto" in those languages.
Continue is OK in "for" loops, and in other loops where the loop
counter is incremented in the condition. However, in any other case,
using "continue" is dangerous, because you can easily end up in an
endless loop if you jump past the loop increment statement.
"break" is the least dangerous, and is actually necessary in "switch"
statements, and OK in loops.
So, my badness hit-list would be:
goto - Eeeeevil ... avoid wherever you can
continue - dangerous in while() and do/while() loops
break - pretty OK to use in "switch" statements, but watch out what
you're jumping over when in a loop.
--
Cheers,
M. Uli Kusterer
------------------------------------------------------------
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.