- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
I know that many good compilers will see the second and convert it to the first, but still...you're willing to take the overhead of a function call just to avoid using GOTO?
Admin
As much maligned as the GOTO is, I've had many, many more headaches caused by large blocks of try/catch blocks with nested if statements thrown in. At least GOTOs like the above can be easily followed.
Admin
WOW. You are an idiot. Please just put your head down on your desk and quit.
Admin
But the common goto is a social being, and rarely stays single - it will magically multiply. Its fur is infested with bugs, but they only come out if there are many gotos around.
Ninjas!
Admin
I actually know of one language where this does in fact happen: the command language used by TI-83+ programs,which is reminiscent of BASIC, but much more math-oriented as to be expected for a calculator - not that that stopped people making games and stuff with it even if it was slow (interpreted, 6MHz 8bit proc, you do the math). Anyway. If you used a looping construct (For, While, Repeat (== Do ... Loop Until)), and Goto'd out of that block, and jump back to start that block again, it would increasingly use up more memory because the interpreter stored the location of each block's start to match with End tokens (one End was used for all blocks). So while this program would never end (until ERR:BREAK'd with the on key)...
... this program would eventually crash to an ERR:MEMORY menu...
It starts becoming clear that memory is being eaten up as the program gets slower and slower, eventually running out of memory entirely (I got to between 620-630 pending loops before it crashed, with 23066B RAM free). It happens because with the language being purely interpreted, it assumes that it's starting a new loop even though it's the same line.
As each Goto would trigger the loop start again, allocating more and more memory for the "start of block" until all RAM (about 24K minus what's chowed up by user data). The memory goes away when the program exits (presumably even if its a subprogram - the closest thing TI-BASIC has to VB Sub/Function) though, much like leaks in other respectable language implementations/operating systems.
I suppose it's possible TFA's poster has used this langauge, encountered this exact scenario, and assumed VB would have the same problem based only on the similar syntax without actually finding out if that was the case? I could see it happen to an interpreted language though, but even VB6 isn't really interpreted. Even if you leave the "Compile on demand" option turned on, it compiles entire subs/functions at a time, presumably to machine code in memory so it's not truly interpreted.
Doesn't excuse using Goto when better options exist though, namely: Exit {Sub|Function|Property|For|Do|While|Select|Try}, Continue (since .NET 2.0), Throw + Try/Catch, and so forth...
Mind you, other than comments, I'd think the goto labels could be good for setting off significant parts of the function, even if never actually jumped to. About the only justification is that IDE autoformatting tends to throw labels up against the left margin (or one indent less than surrounding code) while comments are indented with the rest of the code, so labels could be seen more easily by those who are scanning through for a specific part of a function (and CTRL+F attempts have failed).
Also, C# actually requires goto in one case I can think of namely: switch fallthrough (.NET 2.0 doesn't require for case A: case B: case C: blah, but does require case A: blah; goto case B; case B: blah; - would be nice to see them let you use continue; as a form of explicit fallthrough).
Admin
I consider it harmful to use more complicated constructs solely to avoid using goto.
Your first code snippet is quite clear, easy to read, and efficient. Your second code snippet lacks the efficiency (putting aside "inline" possibilities) and has, IMO, no extra clarity.
In many cases, using goto can increase clarity of code, while also being efficient. In such cases, I argue it should be used. Fanatically avoiding goto can result in duplicating lines of code and /more/ confusing flow of control.
In other cases, using goto massively decreases clarity and maintainability of code. In those cases, I argue it should not be used.
Do most posters in this thread not apply the above logic to most other language constructs? Why is goto somehow exempt? Take a step back and think about it.
Admin
Admin
No, they are not. 'goto' might just jump anywhere, whereas the loop control statements 'continue'/'next'/... and 'break'/'last'/... have precise semantics - the flow of control always continues with the next iteration or the next statement after the loop respectively. Labelled versions allow to transfer control to any labelled enclosing loop other than the one with the control statement.
positively no exceptions from this rule.
The same holds true in principle for 'return' - granted, one can produce some hard-to-read code with 'return's sprinkled all over the place... but still 'return' != 'goto'.
Admin
Yes. If you are coding a VB(A) app for managing your adult DVD collection, you may be right.
If you are talking about production code that you are paid for, you should strongly consider moving into some other profession. but please - nothing where people's lives depend on the quality of your work, like surgeon or pilot, ok? ;o)
captcha: alarm (how extremely fitting...)
Admin
Or perhaps he actually tried to say something meaningful and we all just misunderstood the poor guy ;o) e.g. in german, "Frist" means "time limit", "grace period" or "respite"...
Admin
This reminds me of the paper by W.W.Royce which was written to make a case against using a strict waterfall approach as process model in software engineering. For some unknown reason, only part of the paper was acknowledged, and Mr. Royce - while in fact advocating an iterative approach - was then widely regarded as the inventor of the waterfall model (and he didn't even use the exact term in his paper...).
poor man.
see: http://en.wikipedia.org/wiki/Waterfall_model
captcha: tesla (and yet another widely disregarded man ;o)
Admin
You guys all missed it.. Ahem.
"But the very best thing of all, there's a counter on this ball! Try to beat your very best score, see if you can jump a whole lot more! Skip it, Skip it, Skip it!"
heh now i feel old. furthermore, i hate devo.
Admin
This post was made with the help of beer :-)
Admin
OK, I think I can summarise this:
goto required for assembler.
goto useful for (jumped-up assembly language C). (Although funny that, I've never seen the need.)
goto useful for languages that don't allow multiple exits from a function. (Change yer language, mate.)
goto a wondrous helpmeet for idiots who are so ignorant that it's the only way they can get the thing out the door by 6pm, which is probably their bedtime.
goto like break, continue, etc etc. Um, no. Not really.
goto just like a function call. Last time I looked, function calls involved useful concepts like stacks, and returning to the original caller. Maybe VB.NET has built these in, but I doubt it. The designer isn't idiot enough.
goto a quick solution that can be refactored. Hmm. I've never met a programmer who uses "goto" and "refactor" in the same breath. Don't kill him yet -- I want to study his movements.
And, of course, one great song ...
I trust we're all agreed that the use of goto outside of assembler is disgraceful, and that the original code is very definitely a WTF.
Admin
Hmmm. Well, I agree with your first sentence, but I am not so sure about the examples.
FWIW, I thught more about this later, and remembered using this in VB for the ON Error costruct. That's actually not all that bad in a sub or function that is right-sized. It mainatins locality of reference, and allows for very specific cleanup of errors liely to occur in a specific process.
OTOH, I'm not so sure that it's a good idea to have if blocks nested so deeply that goto is needed. By the time I need more than one leel of nesting, I break out into a different function. By naming a cleanup function clearly, and providing a sensible parameter list, you can achieve the same effect with much greater readability.
Admin
Correct VB6 syntax for exiting a for-next loop:
For Each Thing In BigBagOfThings If SomeCondition Exit For End If ... Next Thing
Correct VB6 syntax for exiting a function:
Public Function CalculateSomething(...) If SomeCondition Then Exit Function End If ... End Function
or, when appropriate
Public Function CalculateSomething(...) If SuppliedParametersAreDodgy Err.Raise .... End If End Function
Goto as a keyword, is redundant in VB6 (not counting it's true-spaghetti uses eg as a replacement for While-Wend).
Nevertheless, I have encountered a number of VB6/VBA programmers who consider my examples above as "confusing" and yet have no problem sprinkling their code with "If Then Goto" as a substitute for nested If/Then blocks.
Splitting nested blocks out into separate functions is NOT always appropriate (and the same programmers often have difficulty with nested function calls that run more than 1 or 2 levels deep).
So why are nested conditional statements such a road block for novice programmers?
Maybe IDEs need to do more to highlight nested structures, in the way that most IDEs now highlight which "(" matches the ")" that one types.
FWIW, the crapocity of VB6 code has been further exacerbated over the years by poorly coded examples in books and online.
Admin
Like the Senator, Harry has examined a videotape of the event and concluded that the coder was not, as commonly believed, brain dead.
Admin
I've often dealt with fast-food counterdroids who act like programs. Get the order sequence wrong (and the sequence may vary from one location to another, even in the same chain) any you get asked for something that you specified two seconds ago. A lot of these bots-in-human-shape can only accept certain facts in answer to an explicit question, so "No cheese. Double burger, just ketchup. No cheese" often results in "Yawantcheezonit?" I thought it was sarcasm until I realized that the counterdroids in question just don't hear the answers to questions that they haven't asked yet unless those answers come in just the right order, just like arguments to a function. There must be something about the work environment that disables real thought. They can't be that dumb off the job, or they would never get to work.
Admin
Every function I build has a GoTo. Why? When I pull in data or set a varible, I set up a quick if statement to make sure we have data. If there isn't data, a quick GoTo skips down, closes recordsets, frees memory, and exit the function. It's not an abuse of the command. The code is structured well and easy to read. A couple of my coworkers started to tear me a new one, when they saw the dreaded "goto". After seeing my limited use of it, they learned to keep their mouths shut. Anyway, maybe it doesn't make me a programming God like you guys. All I know is that my stuff works well, my bosses pay me, and my customer raves. If I'm not cool in your eyes, I'm really not going to lose sleep.
Of course, nesting a bunch of GoTo's in one function is something I would frown upon too. For error catching, I would rather see a GoTo in the code, rather than a SQL error on the user's screen.
Admin
Aaaaaaaaaaaaarrrggghhh!!! I was about to make the very same remark...
Admin
I inherited some VB code that had used Hell: as the general-purpose post-error cleanup point, so lots of functions began with
On Error GoTo Hell
...a vein in which I continued, as I enjoyed the whimsy of it, and the programmer who introduced it was now my boss.
I'm surprised that seemingly no-one's mentioned Knuth's Structued Programming with GOTO Statements paper yet, which at 60 pages says pretty much everything on the subject. So in the interests of redunancy, let me point out my own use for it, in C.
It was essentially hand-transforming some C++ I'd previously written into C, turning the resource-handling wrapper classes into explicit cleanup calls and appropriate flow control.
Except that I had more than 3 levels of resources to deal with, and this approach seemed like it would scale most easily.
captcha: atari. as in atari-go(to)!
Admin
Sorry for WTFing the format, I don't know where all those extra blank lines came from in my last post.
Admin
There's also an article from Donald Knuth entitled "Structured Programming with go to Statements", which I found interesting and borders the subject, although I admit I only read the beginning of the article in passing (so little time, lately :'( ).
Anyway, recently I rememeber using goto's in C#, it was something like this:
SomeReturnType SomeFunction() { // random code block #1
if(someErrorCondition) { goto RaiseException; }
// random code block #2
if(someOtherErrorCondition) { goto RaiseException; }
// random code block #3
if(yetAnotherErrorCondition) { goto RaiseException; }
return someReturnValue;
RaiseException: // some random cleanup and exception throwing code throw someException; }
I did that because I think deep nested if-else statements would be less readable. As a bonus, I could use the same scope, which helped during cleanup, as oposed to using a function wrapping the cleanup/exception code.
Captcha: doom (seems goto's ARE forbidden by the heavens, after all ... oh dear)
Admin
Argh, it ate the indentation.
Admin
Hey, it was good enough for Don, it's good enough for you!
(This is from the actual source code to TeX.)
Admin
If true, then APL would have the most perfect code.
Admin
Admin
The company I work at has salesmen like you. "I've made the sale, now change the product so it does what I promised the customer." As you say, the coders are then forced to put something in quickly and the code quality goes downhill. Fortunately the management are getting wise to this. Some salesmen have had to give up their commission & some have been forced to go back to the customer & admit that the product doesn't do what they said. It's a slow process but we're getting there.
Using your analogy, if we do it properly, one customer may have had to wait for fries but all the future customers get their fries faster.
Admin
ok a little late with the reply, but I just can't let some thing go. ;}
In any case, yes that is the whole problem with the classic goto. Once you've gone where you're going, you no longer know where you've come from. At all. It could be from any random place in the code. You can assume all you want about good programming, and keeping track of things, but the problem is...people aren't very good at that, which is why it shouldn't be done.
Admin
Nope. Joke implies humor. People that post "Frist" or any of their variations aren't funny. They're morons. There's a difference, you know.
Admin
Impossible not, but I have one seldom encounter where goto is the perfect solution: Reinitialization of data.
Following precondition: We have a pretty much iterative language like C. Nothing higher. We have a function with primitive local variables of different type and the language enforces call-by-value. The given data must be preprocessed, rearranged, scaled, whatever. The pecularity is that we have several phases of preprocessing which are quite independent. Let them call A, B and C. After C we must test if the data can be given to the main routine D and the test conditions can be used if and only if all steps A, B, C have been passed. Mostly it passes the test, but on certain and perfectly valid conditions the data must be reprocessed one or more times; depending on the condition A,B,C or B,C or only C. Worse, you must test and jump in exactly this sequence: first if ABC must be rerunned, if BC must be rerunned then if C must be rerunned.
So the one and only perfect and straightforward solution is:
ppA: Execute A ppB: Execute B ppC: Execute C
if (reuseA) goto ppA; if (reuseB) goto ppB; if (reuseC) goto ppC;
Admin
Nope. In 20+ years, the only time I've typed "goto" was just now in this reply.
Your code looks like crap. If you worked for me and wrote code like that, you'd soon be looking for a new job. The goal of anyone with any coding skills should be to write code that's easy to follow and maintain. Yours doesn't meet that goal by any means.
Admin
Can you say "premature optimization"? I'd gladly substitute the function call overhead instead of using a goto, until (extremely doubtful) a profiler tells me otherwise. I doubt very seriously I'll ever see that happen.
Admin
Sure it is. Instead, check your data and, if it's correct, then open recordsets, allocate memory, etc. If it's not correct, exit the function. No ridiculous goto needed.
Or, as an alternative, use a try..finally, and in the finally free the allocated memory, close the datasets, etc. Still no stupid goto needed.
Admin
Another WTF. Erm, may I remind you that 2007-20 = 1987, an era where the C64, the first really successful homecomputer came on the market ? In business and science COBOL and FORTRAN were running on main frames; COBOL to made programming available for non-programmers, FORTRAN for maximum speed (The hardware were comparably slow and computing time precious; it does not help that the early high languages were still of poor quality and/or much slower (The prejudice of the slow functional languages is still rampant)).
And what are you doing here in the first place if you have a firm, hm ? Nothing to supervise or to build ?
So play again with your joystick, daydream again of being the mighty boss and write more convincing baits.
Admin
Uh, mea culpa for all other guys out there who were still there. I forgot C.
Admin
You are correct. "On Error GoTo" is not redundant. My personal WTF is that I mentally count "On Error GoTo" as a separate concept from "GoTo".
And yes, I really have seen GOTO used as a replacement for For-Next or While-Wend.
Adelle.
Admin
You both should burn in hell, for believing goto to be a bad practice in itself. It's a tool. Use it when it helps (very specific, even rare cases), and do not abuse it.
If you take for granted that goto is bad, you should extend that thought to every other language construct and just quit programming altogether, you would provide a great service to humanity in doing so.
Admin
Admin
TRWTF is that VB code is actually featured on The Daily WTF. All VB is a "WTF?"