• 28% Genius (unregistered) in reply to me
    me:
    I hate to say it but I have been tempted by this before.
    Go. Find. Another. Job.

    Seriously. You're not fit to be a programmer.

    This is a case of malicious misquoting. The original author did say that he decided against it.

  • (cs) in reply to xtremezone
    xtremezone:
    There are times where goto is the cleanest, most efficient, and best solution to a coding structure. They are relatively rare though. Saying that goto is only useful under the surface is just as bad as using goto when other control mechanisms should be used.

    Ummm... No. Sorry. Have to disagree.

    I've been writing code professionally for more than 20 years, and as a hobby for several years prior to that. I can count the number of times I typed GOTO easily. Once, in the sentence before this one. I code now in Delphi, but have used several other languages along the way, and never had to clutter my code with that kruft.

  • (cs) in reply to Joe Scylla
    Joe Scylla:
    Well, goto got stigmatized and now many are using Exceptions for flow control (and sometimes write better readable code).

    Goto wasn't that bad.

    Goto was never "bad." It was just one of the first memes to keep programmers from writing tangled code. It's just as easy to obfusticate code with signaling errors, and very likely harder to untangle.

    I write gotos. I use them like EXIT statements to get out of loops. I never, ever use them to branch into a loop.

  • (cs) in reply to brazzy
    brazzy:
    According to that line of reasoning, any kind of code that handles specific exceptions is stupid, because it obviously expects that exception, so the exception should not have been used.

    You're being too literal with your interpretation of expecting.

    Using an exception for something you know may happen, but shouldn't in normal cases, is appropriate. As you said, using them for flow control is always wrong. I guess we meant the same thing, but obviously your phrasing was much better than mine. :-)

    My point was that, if they were for handling normal branching in the code, they wouldn't have been called "exceptions"; instead they'd have been called "NormalOps", or "CodeBranch" or something.

    I'd agree 100% with everything else you said as well.

  • Chazz (unregistered) in reply to Ian
    Ian:
    he probably did this because .Net throws an exception if you do a redirect inside a try block. You have to either redirect with the 'endResponse' flag set to false, or catch a ThreadAbort exception and ignore it.

    My guess is that the try block exists for the sole purpose of throwing the RedirectException in it.

  • Chazz (unregistered) in reply to KenW
    KenW:
    xtremezone:
    There are times where goto is the cleanest, most efficient, and best solution to a coding structure. They are relatively rare though. Saying that goto is only useful under the surface is just as bad as using goto when other control mechanisms should be used.

    Ummm... No. Sorry. Have to disagree.

    I've been writing code professionally for more than 20 years, and as a hobby for several years prior to that. I can count the number of times I typed GOTO easily. Once, in the sentence before this one. I code now in Delphi, but have used several other languages along the way, and never had to clutter my code with that kruft.

    Have you ever used a switch statement? Essentially a fancy set of if/then statements with GOTOs.

  • (cs) in reply to Iago
    Iago:
    I'm fed up of the claim that "you shouldn't use exceptions for control flow because exceptions are supposed to be exceptional". That's like saying "you shouldn't use read-only variables because variables are supposed to be variable".

    There's no such thing as a "read-only variable". A "read-only variable" doesn't exist. If you can't change it, it's a constant. If you can change it, it's a variable. Be fed up all you like - you shouldn't use read-only variables, because they don't exist.

    Iago:
    That which we call a variable by any other name would still be a name bound to a value that might or might not be mutable.

    And, as I explained above, you're wrong. It's not a variable by definition if you can't change it's value. It's a constant. Calling it a variable is like calling a car a table; they're not the same thing at all, and referring to them as the same thing is simply wrong.

    Iago:
    And that which we call an exception by any other name would still be a structured, highly-constrained form of goto with the ability to propogate arbitrary data up the call stack to the first relevant handler.

    Look at what a construct does and how it affects code maintainability, not what English words its name resembles.

    Look at the reality of the situation, and not your imaginary idea of the way things are. A constant is not a variable, a variable is not a constant, and an exception is not a flow control mechanism.

    Seriously, if you can't understand the difference, you should find another line of work.

  • (cs) in reply to Bill
    Bill:
    Well that was a pretty weak response, as others have noted...

    But if you think having an idea for a different use for a tool renders one unfit to program you should probably head back to ITT... of course that you didn't quote the second half indicates that this is just a troll.

    Shit, I am responding to a troll, and not a bright one at that.

    And apparently talking to yourself, as we have no idea who else you'd be referencing. Perhaps you should see someone about those voices in your head? :-)

  • 28% Genius (unregistered) in reply to SomeCoder
    SomeCoder:
    Gordon:
    <snip> I was brought in to maintain a C (not C++) program
    <snip>

    Umm... ok. I'm maintaining some code that does just this (except it's C++ code, not C).

    <snip> FAIL.

    I've give you that gotos might have some use... in really obscure situations. But overall, it makes for a maintainability nightmare.

    Remember that C does not have exceptions. An alternative would be like:

                if (SomethingIsHorriblyWrong) {
                    errorflag = ReallyBadError;
                }
                
                if (errorflag == NoError) {
                    DoSomeThing();
                    if (SomethingElseIsHorriblyWrong) {
                        errorflag = AnotherReallyBadError;
                    }
                }
                if (errorflag == NoError) {
                    DoSomeThingElse();
                    if (SomethingElseIsHorriblyWrong) {
                        errorflag = AnotherReallyBadError;
                    }
                }
    
        ...
    
    
        // cleanup
    
        ...
    
        return errorflag;
    

    This gets tedious real quick. Another thing you can do is to just let the ifs nest as far as needed, but that doesn't make the code very clear.

    I think that the use of goto as described by Gordon is a good replacement for exceptions in languages that don't have them.

  • MindChild (unregistered) in reply to Matt

    A lot of you, even the ones who deal with something lower level such as C/C++ probably never have been put into a situation where using a goto did the bad things you were supposed to avoid.

    When doing your for loops or if statements, it tends to get translated into a 'jnz' or 'jz' instructions. These are short jumps and usually don't cause what is called a 'branch penalty', where the CPU read-ahead cache is flushed. A goto however, unless short in scope and optimized properly by the compiler, can very well jump outside of the bounds of the cache, causing a branch penalty usually.

    Today, caches are bigger, and optimizers are better, and cpus/ram are faster. You can use a goto without the blaring performance hits of yesterday.

    The issue comes along though, that some of you may not always be writing code that targets an x86. I learned all about this stuff when I was thrown knee deep into having to program a 68000 based phone switch microcontroller. Having good practices always is a better idea, rather than just saying "Meh. I'll never have to deal with that"

  • (cs) in reply to iNFiNiTyLoOp
    Okay you goto haters, how would you refactor this? (It could ping-pong many thousands of times a second, so recursion is out.) These are the only two gotos in the program.
    if( irreleventMode1 )
    { //...
    		
    }
    else if( irreleventMode2 )
    { //...
    		
    }
    else if( pingPongForwardsMode || pingPongBackwardsMode )
    {
        while (!(buffer is full))
        {
            Add sample from playback position to the buffer;
            if (pingPongForwardsMode)
            {
                incremet playback position ;
                if (playback position == endOfLoop)
                {
                    set mode to pingPongBackwardsMode ;
                }
            }
            else // pingPongBackwardsMode
            {
                decrement playback position ;
                if (playback position < beginningOfLoop)
                {
                    set mode to pingPongForwardsMode ;
                }
            }
        }
        return ;
    }
    else // other stuff
    

    There you go. I even preserved the playback position overruns.

    It's a matter of taste, but I think my version is clearer.

  • (cs) in reply to dolor
    dolor:
    Absoultely not. This attitude makes exceptions seem like they're supposed to be used very rarely - so people still use return codes and other half-baked ideas instead of elegant exceptions.

    Wrong. Exceptions are supposed to be used rarely, to handle issues in the code that are not to normally occur. That's why they're called "exceptions".

    dolor:
    Running to the end of a file is perhaps not 'exceptional' but is much cleaner to deal with. The supposed overhead in dealing with exceptions is, for the vast majority of situations, dwarfed by the extra cost and confusion in writing hacky stupid code.

    Aside: Gotos are bad because they allow for multiple ENTIRES to a code block. Exceptions only allow for multiple EXITS.

    Running to the end of file is not exceptional, but is not normally encountered, and therefore an exception is fine to handle that unusual (exceptional) condition. See? That's why they call them exceptions.

    And not using exceptions inappropriately doesn't result in "hacky stupid code", unless you're a hacky stupid programmer. Using them where you shouldn't just adds overhead to your code, slows down execution of your application, and shows people you don't know what you're doing. Maybe that works for some people; it doesn't for me.

  • (cs) in reply to Chazz
    Chazz:
    Have you ever used a switch statement? Essentially a fancy set of if/then statements with GOTOs.

    Ummm.... Have you ever coded directly in binary? Essentially a fancy set of if/then statements as well.

    Your point is missing the whole concept of readability and maintainability, which goto impedes. Spaghetti code is the usual result of goto usage. Trying to justify it by comparing it to more maintainable and understandable code structures is like trying to justify coding directly in machine code because they eventually end up doing the same thing. The machine code isn't as maintainable or legible, which is why we don't code in it.

  • TopicSlayer (unregistered) in reply to brazzy

    Yes, they do propogate up the stack quite nicely. In a fashion that quite resembles throwing a ball into an out-field full of blind players. Someone may catch it, but maybe the ball crashes to the ground.

  • phlyingpenguin (unregistered)

    This is essentially how CherryPy does things. It's acceptable to

    raise cherrypy.HTTPRedirect(location)
    in order to ask for a redirect. See the tutorial linked off of the official CherryPy site!

    http://genshi.edgewall.org/wiki/GenshiTutorial#AddingaSubmissionForm

  • The Constant Programmer (unregistered) in reply to KenW
    KenW:
    It's not a variable by definition if you can't change it's value. It's a constant. Calling it a variable is like calling a car a table; they're not the same thing at all, and referring to them as the same thing is simply wrong.
    If we're used to a decent programming language, which has constants for things that are constant, then you're obviously right.

    On the other hand, just look how some highly illogical languages such as Perl need to jump through hoops if you want a constant in your program.

    (In Perl, constants do not seem to be provided by the core language; you can use an extension module, which simulates constants by apparently setting up a function behind the scenes, which always returns the same value.)

    I suppose it would be the same on a machine-language level; a constant is something somewhere in memory, so you could always overwrite that memory location if and when you feel like it...

    So Iago may still be right, in a sense. That which we call exception by any other name is still just a bunch of zeroes and ones in some memory chip or one some hard disk... ;-)

  • AdT (unregistered) in reply to DZ-Jay
    DZ-Jay:
    Or, an easier (and may I say, better) solution is to send "False" as the second argument to Response.Redirect() which will prevent the thread from being aborted, and code properly your exit path.

    As was mentioned several times before, like in the featured post I responded to.

  • Andrew (unregistered) in reply to Matt

    If you do much programming in ASY, you use GOTO dirivatives alot!

  • nicolás (unregistered) in reply to Matt

    GOTOs are evil because the principle of locality (on which all caches are based on ) fails when code jumps indiscrimantly.

  • Anonymous Coward (unregistered)

    Smells a lot like Enhydra's ServerPageRedirectException (http://kickjava.com/src/com/lutris/appserver/server/httpPresentation/ServerPageRedirectException.java.htm), which is even worse because it's actually part of the framework.

  • ex-Pizza delivery man (unregistered)

    Once you've got into a few nested loop levels and your conditional logic is getting complicated, for the sake of readability its much better to use a goto with a properly named label (like end_of_outer_loop) to break out of it than to start playing with boolean algerbra hell and introducing loads of flags.

  • Dan (unregistered) in reply to Chazz
    Chazz:
    Have you ever used a switch statement? Essentially a fancy set of if/then statements with GOTOs.

    switch == GOTOs. WTF

  • (cs) in reply to SomeCoder
    SomeCoder:
    Umm... ok. I'm maintaining some code that does just this (except it's C++ code, not C). Let me introduce you to a little error, I like to call the "jump to label" error:
    vector<string> someVector;
    
    if (some error) goto end;
    
    // Add elements to the vector here.
    
    vector<string>::iterator begin = someVector.begin(); // This line causes an error because of the goto
    
    vector<string>::iterator end = someVector.end(); // This line also causes the error
    
    ...<snip>...
    
    end: 
       // clean up... etc.
    
    

    Resulting error message (using g++) "error: jump to label 'end' error: crosses initialization of 'vector<string>::iterator begin'

    FAIL.

    I've give you that gotos might have some use... in really obscure situations. But overall, it makes for a maintainability nightmare.

    May I ask which version of g++? Using g++ (3.4.5) from MinGW in Windows and g++ (4.1.1) from GCC in Linux, the following code compiles and runs as expected...

    #include <iostream>
    #include <vector>
    
    int main(int, char*)
    {
        std::vector<std::string> v;
    
        if(true)
            goto main_cleanup;
    
        v.push_back("foo");
        v.push_back("bar");
        v.push_back("baz");
    
        for(std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++)
            std::cout << *i << std::endl;
    
    main_cleanup:
    	return(0);
    }
    

    There is no output. If you comment out the if and goto the program outputs...

    foo
    bar
    baz

    Is that not what you said would cause the error(s)? O_o

    Addendum (2008-04-09 13:34): Compiled with...

    g++ -O2 main.cpp -o test.exe
    g++ -O2 main.cpp -o test

  • wolfy (unregistered) in reply to KenW
    KenW:
    Iago:
    I'm fed up of the claim that "you shouldn't use exceptions for control flow because exceptions are supposed to be exceptional". That's like saying "you shouldn't use read-only variables because variables are supposed to be variable".

    There's no such thing as a "read-only variable". A "read-only variable" doesn't exist. If you can't change it, it's a constant. If you can change it, it's a variable. Be fed up all you like - you shouldn't use read-only variables, because they don't exist.

    Iago:
    That which we call a variable by any other name would still be a name bound to a value that might or might not be mutable.

    And, as I explained above, you're wrong. It's not a variable by definition if you can't change it's value. It's a constant. Calling it a variable is like calling a car a table; they're not the same thing at all, and referring to them as the same thing is simply wrong.

    Iago:
    And that which we call an exception by any other name would still be a structured, highly-constrained form of goto with the ability to propogate arbitrary data up the call stack to the first relevant handler.

    Look at what a construct does and how it affects code maintainability, not what English words its name resembles.

    Look at the reality of the situation, and not your imaginary idea of the way things are. A constant is not a variable, a variable is not a constant, and an exception is not a flow control mechanism.

    Seriously, if you can't understand the difference, you should find another line of work.

    You are just so right...the constant ;o) misunderstanding/misuse of the term "constant" might stem from the fact, that not many (or at least not enough) developers know the term "literal".

    Literals are commonly called "constants" by many people, which leads to

    *) either not having a term left for "real" constants (i.e. "variable" declarations with some constant/final keyword), therefore resorting to dumb workarounds like "read-only variable"

    *) or using the same term interchangeably for two very distinct concepts...

    Go ahead and ask all the developers you can get hold of how they call constructs like

    "hello"

    or

    5.3

    in code - I bet more than 50% will answer "Constants of course!".

    Then ask those who did to name all parts in lines like

    const int i = 8;

    or

    final int i = 8;

    Wanna bet?

    "Why, of course this is a read-only variable initialized with a constant!" ;o))

  • Robin Goodfellow (unregistered) in reply to Steve
    Steve:
    Woohoo:
    4) not knowing about the "return" statement (!!!)

    number 4 is the real killer, of course... ;o)

    There are some schools of thought which abjure the use of
    return
    statements other than as the last line of a function or method.

    FYI, those schools of thought are wrong.

  • anders (unregistered)

    Those of you who are fanatically against Exceptions for non-exceptional things: What do you make of the python StopIteration exception?

    It's used for iterators to signal the end of a sequence.

    I find it very clean and easy to use. Just because Exceptions may have been invented for exceptional cases (although I even doubt that, since it's hard to define 'exceptional'), doesn't mean they can't be useful for other things.

    Doesn't it all boil down to how useful and productive you get (counting maintenance, not just development, of course)?

    Zealotry in all forms annoys me...

    There may be good arguments against most uses of goto, but are there really good arguments for banning Exceptions except for error handling?

  • (cs) in reply to nicolás
    nicolás:
    GOTOs are evil because the principle of locality (on which all caches are based on ) fails when code jumps indiscrimantly.

    Sorry, but that is just plain wrong.

    Yes, caches like 'locality', but the only way you could achieve that would be to have one long function which goes through from beginning to end, with only small loops in.

    Once you make a function call, you're breaking 'locality' - probably far more than using a goto within the same function.

    Gotos also don't break pipelining, since a 'goto' is an unconditional jump, so the pipeline fetcher can predict with 100% accuracy where it's going to go to and start pre-fetching from the correct place. A switch or if/then is far less predictable than a goto for a pipeliner.

    In any case, if your choice is between 'goto' and an exception, and performance is your deciding factor (which it must be if you're talking about cache effects), then goto is a very clear winner! Exceptions can take thousands of times longer than a goto. A goto is a VERY fast operation.

    The only reason not to use a goto within a function is readability. That's a strong enough reason, there don't need to be any others.

    (As other people have said, lots of C++ operations are really 'gotos in disguise' so any cache/pipeliner disadvantages would hit those just as much).

  • (cs) in reply to xtremezone
    xtremezone:
        goto main_cleanup;
    
    v.push_back("foo");
    v.push_back("bar");
    v.push_back("baz");
    
    for(std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++)
        std::cout << *i << std::endl;
    

    main_cleanup:

    Is that not what you said would cause the error(s)? O_o

    The scope of the iterator is within the loop construct - the goto doesn't reach a place where the iterator is in scope, but hasn't been initialised.

    So, no, it's not the same problem at all. Jumping into the for() loop, though ...

  • (cs) in reply to Bellinghman
    Bellinghman:
    The scope of the iterator is within the loop construct - the goto doesn't reach a place where the iterator is in scope, but hasn't been initialised.

    So, no, it's not the same problem at all.

    I see what you mean now. I don't think that should ever be an issue in my code because I declare all of my variables at the top of their scope.

    #include <iostream>
    #include <vector>
    
    int main(int, char*)
    {
        std::vector<std::string>::iterator i;
        std::vector<std::string> v;
    
        if(true)
            goto main_cleanup;
    
        v.push_back("foo");
        v.push_back("bar");
        v.push_back("baz");
    
        for(i = v.begin(); i != v.end(); i++)
            std::cout << *i << std::endl;
    
    main_cleanup:
    
        return(0);
    }

    ...which seems to avoid such an error.

    Addendum (2008-04-10 15:19):

    I would normally declare a for-loop control variable or iterator inside the for-loop's initializer, but I was demonstrating that by declaring the variable above the goto you seem to avoid the error mentioned earlier.

  • Die Gotos Die (unregistered) in reply to OzPeter
    OzPeter:
    What I find ironic is the the aboslute belief that Goto's are bad, yet when you get down to the bare metal thats fundementally what a CPU runs on.

    Computers use GOTOs. Programmers abuse them. The reason for this is that the computer has a nice, accurate data structure containing all the source/destination addresses, can follow the references instantly, and never blinks/mis-clicks/changes the source code. Humans, on the other hand, are lucky if they can remember what file they're currently editing, let alone being able to figure out the spaghetti code that some jerk who thinks he's as smart as the compiler wrote 5 years ago.

    In short, don't use GOTOs, as the compiler is infinitely better at it than you.

  • (cs) in reply to Die Gotos Die
    Die Gotos Die:
    In short, don't use GOTOs, as the compiler is infinitely better at it than you.
    You're overlooking that in rare cases goto is the best solution, and once again, not using it when it's appropriate is just as much of a WTF as it is to use it at the wrong time.

    Obviously this was the wrong time...

  • (cs) in reply to dave

    I found code I inherited at work that did Int32.Parse("abc") to do flow control (break out of a loop in that case). That's just one of the things that makes me cry here.

  • Mikael Bergkvist (unregistered) in reply to Matt
    Matt:
    OzPeter:
    Joe Scylla:
    Well, goto got stigmatized and now many are using Exceptions for flow control (and sometimes write better readable code).

    Goto wasn't that bad.

    What I find ironic is the the aboslute belief that Goto's are bad, yet when you get down to the bare metal thats fundementally what a CPU runs on.

    Like all things Goto's are a tool, and its the misuse of the tool that is bad, not the tool itself (damn am I starting to sound like an NRA spokesperson???)

    GOTOs don't kill applications- Programmers kill applications.

    No, no, users kill applications.

  • (cs) in reply to FIA
    FIA:
    OzPeter:
    And yes I also had to invent a time machine in order to get to work 10 hours before I got up in the morning after spending 14 hours walking up hill each way in a snow storm

    Invent a time machine? That's nothing. Back in my day we 'ad to invent time itself, which we'd 'ewn from the primordial soup, and come up with a supporting mathmatical model (with equations) to explain it 't pit owner, that's before 47 'our walk home on our bare hand, at which point father'd declare us an imaginary construct and we'd cease to exist; and be bloody glad of it too.

    In old country, we not have old country jokes, so we had to make do with original jokes instead.

  • (cs) in reply to Die Gotos Die
    Die Gotos Die:
    In short, don't use GOTOs, as the compiler is infinitely better at it than you.
    For some reason (possibly the use of the word "infinitely"), this makes me think of a version of the originally-posited Turing machine -- a roll of paper and a pencil -- with all the possible answers in the universe inscribed on it. I can see how the compiler could direct you to the correct answer, merely by arranging a suitable number of GOTOs. (The actual details of how to do this on a strip of paper are too painful to go into here.) I'd also have to believe that it would have to be one hell of a smart compiler.

    The bottom line, as you say, is that anybody who uses a GOTO in anything other than tight OS kernel code is a dingbat. Arguments about breaks, continues, exits, etc etc are irrelevant to this. These keywords form part of a higher-level semantic; how they are implemented is irrelevant. GOTO is an assembler-level semantic (thus causing significant pain whilst unwinding stacks and freeing memory); and it's not even implemented as a GOTO in assembler, anyway. It's implemented as a "Jump Immediate."

  • Paulo Faustino (unregistered)

    If you've been getting those kind of errors after using Response.Redirect use this aproach:

    Response.Redirect("somefile.aspx", true); HttpContext.Current.ApplicationInstance.CompleteRequest();

  • ckelloug (unregistered)

    The reason not to do returns in the middle of code is that it increases the McCabe cyclomatic complexity. Cyclomatic complexity is a metric used in analyzing complexity and error-proneness of code. Most people have long forgotten the why of not doing the return in the middle of the code.

    IMHO, the return in the middle of the code can make thing much simpler and less error prone in actuality even if it does increase the mathematical measures of complexity. If you return in the middle of the code, you don't have to ensure that you didn't accidentally execute other code (due to mistakes in tests before the return) before you actually return.

  • Mozilla Ate My Brain (unregistered) in reply to FDumlao
    Oh, and GOTO's r teh suck. Not because they cause a performance problem - because they are hard to friggin read. They cause a linear line of thought in your brain to have to branch off to some other part of the code. It's ugly too. If you need to break that code out why not just write a private method to handle it?
    Because a private method causes you to have to branch off to some other part of the code? I mean, seriously, you might as well argue against methods and subroutines with that logic. Yes, I know Dijkstra went to some effort to distinguish gotos from procedures, but I doubt if he'd ever seen a case of Spaghetti Inheritance in 1968.
  • (cs) in reply to Mozilla Ate My Brain
    Mozilla Ate My Brain:
    Oh, and GOTO's r teh suck. Not because they cause a performance problem - because they are hard to friggin read. They cause a linear line of thought in your brain to have to branch off to some other part of the code. It's ugly too. If you need to break that code out why not just write a private method to handle it?
    Because a private method causes you to have to branch off to some other part of the code? I mean, seriously, you might as well argue against methods and subroutines with that logic. Yes, I know Dijkstra went to some effort to distinguish gotos from procedures, but I doubt if he'd ever seen a case of Spaghetti Inheritance in 1968.
    Ahem.

    OOP though the comment might be, I see no difference between a "private method" and a Fortran function or procedure, so far as this argument goes. I'd suggest that this is a pretty reasonable representation of Dijkstra's opinions.

    I'd imagine that "branching off to some other part of the code" is short-hand for "fighting the IDE to find the corresponding label, twenty-three pages down." I'd love to agree that this is "as hard to friggin read" as a call to DoLotsaCommonStuff(...), but, on the whole, I'd rather be in Philadelphia.

  • M4 (unregistered) in reply to dkf
    dkf:
    OzPeter:
    Like all things Goto's are a tool, and its the misuse of the tool that is bad, not the tool itself (damn am I starting to sound like an NRA spokesperson???)
    Welcome to the NGA - the National Goto Association. Tonight we're having pasta for our association dinner; spaghetti, to be exact.

    But spaghetti code is not so bad, just start pulling the strands and it will unravel. Macaroni code however is something else.

    And no, this is not really a joke. Having refactored hundreds of programs, I can tell there really is such a difference.

    M4

  • (cs)

    I have to quote my own WTF here from my MP3 player frontend:

    FCGI.each_cgi() do |cgi|
        str = nil
        type = "text/html; charset=utf-8"
        begin
            viewonly = ...
            bofh = ...
            viewonly, bofh = false, true if ["192.168.1.4", "127.0.1.1"].include?(cgi.remote_addr())
            #raise ExpectedException, cgi.remote_addr()
            ret = nil
            cmd = (cgi.path_info() || "").sub(%r{.*/}, "").gsub(%r{[^A-Za-z]}, "")
            case
                when cmd == "queue"
                    ret = queue(viewonly, bofh)
                when cmd == "cancel" && !viewonly
                    ret = cancel(cgi["i"])
                when cmd == "setnext" && !viewonly
                    ret = setnext(cgi["i"])
                when cmd == "kill" && !viewonly && bofh
                    ret = killPlayer("INT", cgi["i"])
                when cmd == "pause" && !viewonly && bofh
                    ret = killPlayer("STOP", false)
                when cmd == "unpause" && !viewonly && bofh
                    ret = killPlayer("CONT", false)
                when cmd == "search" && !viewonly
                    ret = searchFile(cgi["q"])
                when cmd == "enqueue" && !viewonly
                    ret = enqueueFile(cgi["f"])
                when cmd == "stylecss"
                    raise HTMLStylesheet
                else
                    raise ExpectedException, "Polite webservers would now tell you to 404 off."
            end
            str = $html % [ret]
        rescue HTMLRedirect => r
            str, type = $html_redirect % [r.message], {
                "type" => "text/html; charset=utf-8",
                "status" => "REDIRECT",
                "location" => r.message
            }
        rescue HTMLStylesheet => s
            str, type = $html_css, "text/css"
        rescue XMLRPC::FaultException => e
            str = $html_error % [CGI.escapeHTML("#<XMLRPC::FaultException: %s>" % [(e.to_h()).inspect()])]
        rescue Exception => e
            str = $html_error % [CGI.escapeHTML(e.inspect())]
        end
        cgi.out(type) do
            str
        end
    end
    

    And yes, it does do all sorts of nasty stuff, like catching EVERY exception... but hey, it works.

  • Tom_fan_63 (unregistered) in reply to T
    T:
    In certain situations throwing something is somewhat more elegant, and while it is not recommended, it is certainly not frowned upon

    Elegant??? Do you understand what are you talking about??? Are you in the fashion vortex or are you trying to do your job creating programs that CAN (possibly) be maintained by other professionals like "you" (sigh...)

  • Tom_fan_63 (unregistered) in reply to KenW
    KenW:
    xtremezone:
    There are times where goto is the cleanest, most efficient, and best solution to a coding structure. They are relatively rare though. Saying that goto is only useful under the surface is just as bad as using goto when other control mechanisms should be used.

    Ummm... No. Sorry. Have to disagree.

    I've been writing code professionally for more than 20 years, and as a hobby for several years prior to that. I can count the number of times I typed GOTO easily. Once, in the sentence before this one. I code now in Delphi, but have used several other languages along the way, and never had to clutter my code with that kruft.

    Well said!

  • Tom_fan_63 (unregistered) in reply to iNFiNiTyLoOp
    iNFiNiTyLoOp:
    A while ago I wrote some FastTracker (*.xm) playback routine that seemed to need goto. FastTracker can play back sounds in different modes, one of them being ping-pong. Ping-pong will alternate between forwards and backwards playback, reversing direction between the loop points.
    if( irreleventMode1 ){ //...
    }else if( irreleventMode2 ){ //...
    }else if( pingPongForwardsMode ){
      pingPongForwards:
      while( playbackPosition < endOfLoop ){
        Add sample from playback position to the buffer;
        increment playback position.
        if( buffer is full ) return;
      }
      goto pingPongBackwards;
    }else if( pingPongBackwardsMode ){
      pingPongBackwards:
      while( playbackPosition >= beginningOfLoop ){
        Add sample from playback position to the buffer;
        decrement playback position.
        if( buffer is full ) return;
      }
      goto pingPongForwards;
    }
    

    Okay you goto haters, how would you refactor this? (It could ping-pong many thousands of times a second, so recursion is out.) These are the only two gotos in the program.

    What about two subprograms? Do you really think it would be a waste of CPU calling each other instead of evaluate every time? It's really a question, not a statement :-)
  • Kjetil (unregistered)

    This is a brilliant example of exception oriented programming, a very underused way of coding

  • milleniumbug (unregistered)

    GOTOs has some uses. They're rare. So what? GOTOs exist precisely because of them. For example escaping nested loops.

    while ( (c = geth( st )) != 0 )
    {
        puth( c );
        if ( c == '!' )
            while ( (p = geth( st )) != 0 )
            {
                a = a + p;
                if ( p == '*' )
                    goto Outside;
            }
    }
    Outside:;
    
  • Upadłość Konsumencka Sanok (unregistered)

    Upadłość Konsumencka Sanok Pomożemy Ci w złożeniu wniosku o upadłość i poprowadzimy Twoją sprawę kompetentnie i profesjonalnie.

    • Upadłość Konsumencka Sanok https://sites.google.com/view/upadlosckonsumenckasanok/
  • Kancelaria Upadłość Konsumencka (unregistered)

    Wow that was strange. I just wrote an really long comment but after I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again. Anyway, just wanted to say fantastic blog! https://sites.google.com/view/kancelaria-upadlosc/home

  • pozycjonowanie sky-shop (unregistered)
    Comment held for moderation.
  • pozycjonowanie sky-shop (unregistered)

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates. http://www.aotingmei.com/bbs/board.php?bo_table=free&wr_id=144838

Leave a comment on “The RedirectException”

Log In or post as a guest

Replying to comment #:

« Return to Article