• (cs) in reply to An Old Hacker

    And the REALLY REALLY sad part is that all loops, in just about any language, such as "while" and "for" are really implemented using GOTOs!

    Okay, the really sad part is that people think jumps/gotos in the compiled assembly instructions are a sad part of a programming language.

  • (cs) in reply to An Old Hacker
    An Old Hacker:
    Frank:
    AssBlaster:
    Multiple return points are bad for the same reasons GOTO's are mostly bad. Also, they tend to be used a lot by people who don't know what an exception is.
    And what if you're programming in a language which doesn't have built-in exception handling, like C? I've seen C code which was a horrific tangled mess because the project lead declared that every function must have only 1 return point. As a result, after every function call was an if-structure designed to make sure the calling function would only continue if the called function returned successfully. At the end of each function was a huge pile of closing brackets. God help you if mistakenly deleted an opening bracket a page earlier. The result was code which I found to be very un-maintainable. It really made me say "WTF?"

    Your point is well taken if you are implementing exceptions. But even in a language which supports exceptions natively, exception handling can result in much slower code. Thus, it is often not used in embedded code. In that case, I think multiple return points can actually result in much faster and more maintainable code.

    The really sad part about that is, afaik, in C, there really is only one return point. A return inside the method is implemented as a goto the real return...

    And the REALLY REALLY sad part is that all loops, in just about any language, such as "while" and "for" are really implemented using GOTOs!

    Okay, the really sad part is that people think jumps/gotos in the compiled assembly instructions are a sad part of a programming language.

  • (cs) in reply to trtrwtf
    trtrwtf:
    boog:
    hoodaticus:
    The reason is because it's nigh-impossible to tell which path their shitty code took on its way to ruining your day.
    If there are multiple returns, you're looking for the returns. If there's only one return, you're looking for where the return variable was set. I would wager the two tasks are equally difficult, so I'm still not convinced that early returns are necessarily a bad thing.

    Simple answer: the problem hoodaticus is highlighting is methods spanning lots of pages, not multiple points of return.

    Decompose long methods into short single-purpose ones and the early-return problem isn't a problem.

    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.

  • QJo (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    codemonkey73:
    If you are going to use a single return point example write it properly rather than as ugly as possible. Oh, and you fail to return in your multiple return example so that code doesn't even build.
    public bool DoStuff(int someId) {
      var valid = IsValid(someId);
      if (valid) {
        // Do complex processing
      }
      return valid;
    }
    
    First, I'd like to point out that you're being a real pedantic dickweed if you expect code that I quickly wrote in a forum at 3:00AM would compile.

    Anyway, can explain to me why it's necessary to create and assign a local variable and carry its value throughout the method body? If you returned false on !IsValid(), you'd lose two lines of code and a variable (that you no longer have to keep track of while debugging) without losing any readability.

    This also has the nice side-effect of implying that it is in a valid state if it passes that first (or ten) check(s).

    From personal experience whenever you see a single return, the method is usually much more complex than either of our examples. Check out this perfect example of what a badly implemented single return looks like. Why check it four fucking times when you know immediately that you're not going to do any more processing anyway? Just so you have a single return? This makes it that much harder to read and debug for the next developer who has to maintain your code...

    At the end of the day, whatever yields the cleanest, most maintainable and performant (I hate using that word) code should be used. I use both methods, but I will usually lean more towards the early return as it tends to produce code that is more clear, IMHO.

    Think I'm tempted to agree. I looked again at the code I wrote above and have to admit that the immediate return is probably best.

    I have been in a development environment where the "single return" has been a mandatory standard, but then my colleagues were generally second-rate and needed these constraints. The above "set-and-check" technique was the attempt to cleanly implement the single return - it worked, adhered to standards and kept the depth small.

    Another technique I used to use (this was Fortran, so bear with me) was to have a label at the bottom, say 999, which led to a section of code that printed a message based on the current error code status, and either exited the program or returned with an error. Any time one of the (for example) "file read" or "file open" functions failed (and the program could not therefore continue), there would be something like: "IF (ERRSTAT .NE. STATNORM) GOTO 999" after the appropriate file handling statement.

    The alternative would have been an unwieldy sequence of if/then/else which would have got unmaintainably deep, particularly with routines which demanded several files to be open at once.

  • (cs) in reply to valetudo
    valetudo:
    boog:
    ...bad design is bad design. If you have a massive, mostly-messy method that also happens to use early returns, it is not a good example of why early returns are bad. The code just sucks. A good example would show how bad code was improved by only removing early returns. I have yet to see such an example myself.
    Spot on Boogie.... Any argument about creating arbitrary rules ignores the fact that every situation is different.
    Actually, that wasn't my point; I was suggesting that it's wrong to demonstrate a problem by confounding it with another problem.

    But your comment is absolutely correct: different people have different needs, and their decisions (whether obeying an arbitrary "industry rule" or not) should be based entirely on those needs.

  • (cs) in reply to QJo
    QJo:
    C-Octothorpe:
    codemonkey73:
    If you are going to use a single return point example write it properly rather than as ugly as possible. Oh, and you fail to return in your multiple return example so that code doesn't even build.
    public bool DoStuff(int someId) {
      var valid = IsValid(someId);
      if (valid) {
        // Do complex processing
      }
      return valid;
    }
    
    First, I'd like to point out that you're being a real pedantic dickweed if you expect code that I quickly wrote in a forum at 3:00AM would compile.

    Anyway, can explain to me why it's necessary to create and assign a local variable and carry its value throughout the method body? If you returned false on !IsValid(), you'd lose two lines of code and a variable (that you no longer have to keep track of while debugging) without losing any readability.

    This also has the nice side-effect of implying that it is in a valid state if it passes that first (or ten) check(s).

    From personal experience whenever you see a single return, the method is usually much more complex than either of our examples. Check out this perfect example of what a badly implemented single return looks like. Why check it four fucking times when you know immediately that you're not going to do any more processing anyway? Just so you have a single return? This makes it that much harder to read and debug for the next developer who has to maintain your code...

    At the end of the day, whatever yields the cleanest, most maintainable and performant (I hate using that word) code should be used. I use both methods, but I will usually lean more towards the early return as it tends to produce code that is more clear, IMHO.

    Think I'm tempted to agree. I looked again at the code I wrote above and have to admit that the immediate return is probably best.

    I have been in a development environment where the "single return" has been a mandatory standard, but then my colleagues were generally second-rate and needed these constraints. The above "set-and-check" technique was the attempt to cleanly implement the single return - it worked, adhered to standards and kept the depth small.

    Another technique I used to use (this was Fortran, so bear with me) was to have a label at the bottom, say 999, which led to a section of code that printed a message based on the current error code status, and either exited the program or returned with an error. Any time one of the (for example) "file read" or "file open" functions failed (and the program could not therefore continue), there would be something like: "IF (ERRSTAT .NE. STATNORM) GOTO 999" after the appropriate file handling statement.

    The alternative would have been an unwieldy sequence of if/then/else which would have got unmaintainably deep, particularly with routines which demanded several files to be open at once.

    Ha, this is funny: I just wrote a (short) method with a single return because I felt that it made the code clearer. Again, whatever makes the code more readable and maintainable (and obviously wouldn't cause unexpected side-effects or unnecessary processing) is the one I would choose.

    EDIT: The more I think about it the more I realize its really just personal coding style and past experience that will shape which method a person prefers.

  • trtrwtf (unregistered) in reply to boog
    boog:
    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.

    Yeah, I thought I saw more agreement there than disagreement. Sorry to spoil a good argument... now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.

  • (cs) in reply to reductio ad ridiculum
    reductio ad ridiculum:
    Substituting "goto" or "return" for "conjunction" in the little story above is left as an exercise for the reader. Extra credit for turning it into a car analogy.
    And just like it was in school, the extra credit assignment is such a waste of time that I'd much rather waste that time playing video games and just take a B in the class.
  • (cs) in reply to Fat
    Fat:
    Hm.

    I really don't understand what's the big WTF? Can someone explain this to me?

    Sure, there are some additional copies of input parameters, and single return point (which is arguably not a defect), but I think it's not that bad. The code is pretty clear, despite the unfortuante parameters naming. The only bad thing I can see is unnecessary lStr = str every time the replacement is made. In the other hand, the alternative is watching over the difference in lStr and str lengths, which can lead to more complicated code. The guys even managed to escape the infinite loop problem when replacing "a" with "aa", which might be quite elusive.

    On the other hand, if the standard library has case-insensitive Replace, my point is obviously invalid. Is this what the WTF is?

    Yes. Regex.Replace.

  • (cs) in reply to trtrwtf
    trtrwtf:
    boog:
    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.

    Yeah, I thought I saw more agreement there than disagreement. Sorry to spoil a good argument... now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.

    Awesome! Let me get my kit.

  • (cs) in reply to boog
    boog:
    trtrwtf:
    boog:
    hoodaticus:
    The reason is because it's nigh-impossible to tell which path their shitty code took on its way to ruining your day.
    If there are multiple returns, you're looking for the returns. If there's only one return, you're looking for where the return variable was set. I would wager the two tasks are equally difficult, so I'm still not convinced that early returns are necessarily a bad thing.

    Simple answer: the problem hoodaticus is highlighting is methods spanning lots of pages, not multiple points of return.

    Decompose long methods into short single-purpose ones and the early-return problem isn't a problem.

    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.
    Yes, that was your point. I was wrong; boog was right.

  • (cs) in reply to boog
    boog:
    trtrwtf:
    boog:
    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.

    Yeah, I thought I saw more agreement there than disagreement. Sorry to spoil a good argument... now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.

    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!

  • (cs) in reply to hoodaticus
    hoodaticus:
    boog:
    trtrwtf:
    ...now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.
    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!
    With matches!
  • trtrwtf (unregistered) in reply to boog
    boog:
    hoodaticus:
    boog:
    trtrwtf:
    ...now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.
    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!
    With matches!

    Matches? Are we back to regex already?

  • airdrik (unregistered) in reply to trtrwtf
    trtrwtf:
    boog:
    hoodaticus:
    boog:
    trtrwtf:
    ...now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.
    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!
    With matches!

    Matches? Are we back to regex already?

    Only if they burn.

  • mike (unregistered) in reply to boog
    boog:
    To be clear, I'm not questioning the reasons GOTOs are bad - but which of these reasons apply to early returns?

    There are a couple reasons, and in my experience, single return tends to benefit code maintenance tasks. Primarily, it makes it so that the normal (non-exceptional) code flow of a function can be deduced entirely by just looking at the indentation and/or brackets. This is a valuable property for newcomers trying to figure out what a function will do given various inputs.

    Second, in complex functions, single return requires naming the thing you are returning. Combined with good naming, this can help clarify the intent of the original developer.

    Third, it encourages developers to break down huge script-like functions into smaller pieces. Single return naturally causes code to become indented more than code with early returns. Of course, some developers will write 10000-line functions even if it means indenting 100 tabs.

    Some people claim that single return frequently results in contrived code. As a rule of thumb, I find that if I am thinking a function would benefit from multiple return points, the code would probably benefit more from factoring out a helper function.

  • Bored at Work (unregistered) in reply to boog
    boog:
    hoodaticus:
    boog:
    trtrwtf:
    ...now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.
    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!
    With matches!
    Is there any way I could use them to start a flame war?

    USA vs. Britain Imperial Units vs. Metric Grammer Starbucks vs. Tim Hortons Tea Party

  • blah (unregistered) in reply to Jibble
    Jibble:
    On every compiler I've used in the last ten years no extra code is executed unless an exception is actually thrown.
    And have you actually disassembled the object code to verify that this is the case? Every compiler I've seen maintains an exception handler stack outside the call stack, so there's a (very small) overhead for entering or leaving a function that uses exceptions.

    Also, there are some (probably uncommon) cases in C++ that are difficult to compile in a zero-overhead way (array constructors, for example).

  • Fascist Mods are Suppressing My Freedom of Expression (unregistered) in reply to Bored at Work
    Bored at Work:
    boog:
    hoodaticus:
    boog:
    trtrwtf:
    ...now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.
    Awesome! Let me get my kit.
    ZOMG like Dexter's kit!
    With matches!
    Is there any way I could use them to start a flame war?

    USA vs. Britain Imperial Units vs. Metric Grammer Starbucks vs. Tim Hortons Tea Party

    D/S Switching Ass to Mouth Sex with furniture, What do you think?

    Is it the furniture, askistmet? Is IT?

  • trtrwtf (unregistered) in reply to mike
    mike:
    boog:
    To be clear, I'm not questioning the reasons GOTOs are bad - but which of these reasons apply to early returns?

    There are a couple reasons, and in my experience, single return tends to benefit code maintenance tasks. Primarily, it makes it so that the normal (non-exceptional) code flow of a function can be deduced entirely by just looking at the indentation and/or brackets. This is a valuable property for newcomers trying to figure out what a function will do given various inputs.

    Whereas with multiple return, you have to play spot-the-return. Okay, that's reasonable - but in your version you have to track much more nesting. As above, the problem you're describing is one of function length. If you run into this problem, the original writer should be thrown to the zunesis and the problem method refactored until you can take the whole thing in at once.

    Second, in complex functions, single return requires naming the thing you are returning. Combined with good naming, this can help clarify the intent of the original developer.

    I'm sorry, but by observation the return value is always called something like "returnValue" or "returnArray" or whatnot. So there's no information there about what it should be, only what's going to happen to it eventually.

    Third, it encourages developers to break down huge script-like functions into smaller pieces. Single return naturally causes code to become indented more than code with early returns. Of course, some developers will write 10000-line functions even if it means indenting 100 tabs.

    This is an interesting argument. So you're saying that by making long functions so agonizing that no reasonable programmer would write them that long, you're encouraging short functions? The trouble is you're assuming reasonable programmers, but the creators of these monstrosities are obviously neither.

    Some people claim that single return frequently results in contrived code. As a rule of thumb, I find that if I am thinking a function would benefit from multiple return points, the code would probably benefit more from factoring out a helper function.

    This, I can go along with, I suppose. Any time there's an issue of the structure, the first question is: does this function work on too many levels at once? And in the end, either multiple-return or single-return should be equally easy to read.

  • (cs) in reply to mike
    mike:
    boog:
    To be clear, I'm not questioning the reasons GOTOs are bad - but which of these reasons apply to early returns?
    There are a couple reasons, and in my experience, single return tends to benefit code maintenance tasks. Primarily, it makes it so that the normal (non-exceptional) code flow of a function can be deduced entirely by just looking at the indentation and/or brackets. This is a valuable property for newcomers trying to figure out what a function will do given various inputs.
    I'm skeptical about this. It certainly applies to GOTOs because they are invisible spaghetti, but early returns always exit the procedure. With an early return, I know the procedure ends there; without an early return, I have to worry about side-effects in other code that might execute before the return.
    mike:
    Second, in complex functions, single return requires naming the thing you are returning. Combined with good naming, this can help clarify the intent of the original developer.
    I'll agree that developers need to communicate their intent through proper naming, and I'll accept that single returns may encourage this (against my better judgment; every time I see someone create a return variable, it's named "retVal"). But to be fair, this is really only an advantage to single return, not an argument against multiple return - there could still be advantages on the other side, or cases where multiple returns are still a better fit.
    mike:
    Third, it encourages developers to break down huge script-like functions into smaller pieces. Single return naturally causes code to become indented more than code with early returns. Of course, some developers will write 10000-line functions even if it means indenting 100 tabs.
    Developers should be encouraged to structure their code intelligently regardless of whether they are using a single return or multiple returns. Bad design is just bad design.
    mike:
    Some people claim that single return frequently results in contrived code. As a rule of thumb, I find that if I am thinking a function would benefit from multiple return points, the code would probably benefit more from factoring out a helper function.
    To be perfectly honest, I think it doesn't really matter whether a person uses single return or multiple returns; oftentimes it's a personal preference, and rarely is it more beneficial to use one or the other. If the code sucks, it sucks either way. And if a programmer is spending time trying to decide which return style to use, then the sucky code is also late.
  • Nagesh (unregistered)

    Here in Hyderabad, it is featured rule never to be having return statement exception for the last method lines.

  • (cs) in reply to Nagesh
    Nagesh:
    Here in Hyderabad, it is featured rule never to be having return statement exception for the last method lines.
    When you pretend to be Indian, could you make it sound a little less like OCR software is reading out someones alphagetti puke...

    Unless of course you actually are just retarded or a bot, in which case ignore this request.

  • Bob (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    Nagesh:
    Here in Hyderabad, it is featured rule never to be having return statement exception for the last method lines.
    When you pretend to be Indian, could you make it sound a little less like OCR software is reading out someones alphagetti puke...

    Unless of course you actually are just retarded or a bot, in which case ignore this request.

    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

  • (cs) in reply to Bob
    Bob:
    C-Octothorpe:
    Nagesh:
    Here in Hyderabad, it is featured rule never to be having return statement exception for the last method lines.
    When you pretend to be Indian, could you make it sound a little less like OCR software is reading out someones alphagetti puke...

    Unless of course you actually are just retarded or a bot, in which case ignore this request.

    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    Go fu... heh, almost got me there...

  • trtrwtf (unregistered) in reply to Bob
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.

  • Bob (unregistered) in reply to trtrwtf
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.

    This is insane. I can't believe in this day an age, that people can be so insensative. I'm glad that at least I don't have to here about it on TV anymore.

  • (cs) in reply to trtrwtf
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.
    Hahaha! I'm writing that one down. :)
  • frits (unregistered) in reply to boog
    boog:
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.
    Hahaha! I'm writing that one down. :)
    I'm pretty sure writing that comment down could start a flame war.

    Your not too smart, are you?

  • (cs) in reply to Anonymous
    Anonymous:
    [...] After all, it should be obvious from the code!

    Actually had someone assert that here, yesterday. No wonder there are never any comments... sigh.

  • (cs) in reply to Bob
    Bob:
    C-Octothorpe:
    Nagesh:
    Here in Hyderabad, it is featured rule never to be having return statement exception for the last method lines.
    When you pretend to be Indian, could you make it sound a little less like OCR software is reading out someones alphagetti puke...

    Unless of course you actually are just retarded or a bot, in which case ignore this request.

    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

    What, you had a two-year-old bot for a son? My sympathies.

  • (cs) in reply to frits
    frits:
    boog:
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.
    Hahaha! I'm writing that one down. :)
    I'm pretty sure writing that comment down could start a flame war.

    Your not too smart, are you?

    Thank fuck for Bob turning up then, this thread was in danger of turning into profound, intelligent and almost useful. And we don't want that sort of thing around here, thank you very much. Now, can we get back to business, you bunch of snot-gobbling turd-burglars?

  • (cs) in reply to Bob
    Bob:
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.

    This is insane. I can't believe in this day an age, that people can be so insensative. I'm glad that at least I don't have to here about it on TV anymore.

    Why, can you no longer afford one because you've spent all your money on "healthcare" for your substandard offspring?

  • boog (unregistered) in reply to Matt Westwood
    Matt Westwood:
    frits:
    boog:
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.
    Hahaha! I'm writing that one down. :)
    I'm pretty sure writing that comment down could start a flame war.

    Your not too smart, are you?

    Thank fuck for Bob turning up then, this thread was in danger of turning into profound, intelligent and almost useful. And we don't want that sort of thing around here, thank you very much. Now, can we get back to business, you bunch of snot-gobbling turd-burglars?

    That's highly unlikely.

  • jonny (unregistered) in reply to Quote

    first comment i ever laughed out loud...kudos to you and the 2.5 Gearys pale ales i just consumed.

  • (cs) in reply to trtrwtf
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.

    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.

    Are you the one that ripped apart the original gentically-deficient hypersensitive parent? Because that was a truly legendary burn. Seriously - I think it's what caused the high temperatures this summer.

    And what was that about being "thrown to the zunesis"? PRICELESS!

  • (cs) in reply to Dave
    Dave:
    Just wanted to say as a non-coder/hobbyist who likes the DWTF, i appreciated the sarcastic comments in this entry. I muck around with code but I know my (severe) limits and I follow the DWTF as a way of learning. I can usually work out more or less what's wrong with CodeSODs but a lot of it goes over my head. If more entries had this type of comment I'd find it even more useful and entertaining. Cheers and thanks for all the good work.
    Welcome, David! I was you, reading this site a few years ago while coking my way through law school.

    Soon, you will be an elitist code-slinging motherfucker like the rest of us. Just keep reading this site, since it will teach you the attitudes that will guide your coding and make you great.

  • (cs) in reply to An Old Hacker
    An Old Hacker:
    The really sad part about that is, afaik, in C, there really is only one return point. A return inside the method is implemented as a goto the real return...
    It depends on the ABI of the target and optimization. If you are on a target with tons of registers to save/restore and are optimizing for size, then yes it might set the return value, then jump to the part that restores the caller's registers from the stack. Every system is different. I've seen ABIs where the Caller handled stuffing the stack, and ones where the Called function took care of it. More frequently its the latter but you also have platforms with *NO* registers, and everything is done in the stack, zero page, or local offset.
  • Greg (unregistered) in reply to Frank

    Instead of multiple returns, I allow myself one goto (and ONLY one which is named the same and serves the same purpose in every function): goto _exit;

    The end of my functions look like this:

    ret = SUCCESS; _exit: // cleanup mem/FPs. .... return(ret);

  • Markus (unregistered) in reply to boog
    boog:
    private bool MatchWord(ref string str, bool checkCase, bool checkWholeWord, string strFind)
    {
         // declare a local that will be returned; it's prefered to use only one "return" statement, at the end
        bool changed = false;
        changed = ChangeWord(str, checkCase, checkWholeWord, strFind, strFind);
        return changed;
    }

    FTFY.

  • L. (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    First, I'd like to point out that you're being a real pedantic dickweed if you expect code that I quickly wrote in a forum at 3:00AM would compile.

    I also do sometimes fail as you did sir, and I believe it to be a shame and a proof that I'm not a machine yet.

    So yeah, machine-ify yourself goddamit !!

  • (cs)

    What's wrong with this way of using multiple returns? (apart from the fact that there exists a TryParse method in the framework)

    // This method reads an int from a file, returns null if it
    // cannot be read
    int? TryParseFile(string file)
    {
        if (file == null || !File.Exists(file))
            return default(int?);
    
        try
        {
            using (var sr = new StreamReader(file))
            {
                return int.Parse(sr.ReadToEnd())
            }
        }
        catch (IOException)
        {
            return default(int?);
        }
    }
    
  • L. (unregistered) in reply to trtrwtf
    trtrwtf:
    boog:
    True true - that's kind of what I was addressing in the second part of my comment (which wasn't quoted above): if you have a method that spans lots of pages, that's the problem, not early returns.

    Yeah, I thought I saw more agreement there than disagreement. Sorry to spoil a good argument... now let's go out and burn down a barn, after filling it with programmers who write 20-page functions and then goto the middle of them.

    Spot on . The main thing I do when I refactor, is make functions short. There's nothing that's 10 (real, not 867 character long) lines long AND unreadable ... well almost nothing.

    Same .. I don't see how a goto in a 10 line function could confuse anyone, neither could if/else madness or early returns.

    Take that up to 20 lines it's still manageable .. maybe even 30 (that's all the indentation you need, stop there thanks.)

    CAPTCHA:"tation" .. err what-tation ?

  • azathoth (unregistered)

    The benefit of a single return is that it's possible to add tracing of the return value in a single place.

    The benefit of multiple returns is you can use them to enforce clear constraints on a function making code very readable.

    bool CanFireAt(Target t)
    {
      if (!alive)
        return false;
      if (weapon == NONE)
        return false;
      if (!IsVisible(t))
        return false;
      return true;
    }
    
  • L. (unregistered) in reply to azathoth

    Nice example . sorts of goes back to what I wrote above about function length and it's better looking than if(){if(){if(){}}}return $return;

  • Someone who's ego (or something...) is growing (unregistered) in reply to hoodaticus
    hoodaticus:
    that was a truly legendary burn. Seriously - I think it's what caused the high temperatures this summer.

    And what was that about being "thrown to the zunesis"? PRICELESS!

    +1 :)

  • Someone who's ego (or something...) is growing (unregistered) in reply to Matt Westwood
    Matt Westwood:
    Bob:
    trtrwtf:
    Bob:
    Hey, I had a kid who was mentally challenged, and let me assure you that it is nothing to joke about. Please do not use this word flippantly.
    The real WTF is that your kid being mentally challenged is something noteworthy. If our schools don't challenge all of our children mentally, it's no wonder they end up as retards.
    This is insane. I can't believe in this day an age, that people can be so insensative. I'm glad that at least I don't have to here about it on TV anymore.
    Why, can you no longer afford one because you've spent all your money on "healthcare" for your substandard offspring?
    Maybe he could make the money by "renting out" the child in question. It's not like they would understand what was going on.

    Hmmm... That makes me wonder... is it legal to EVER engage in intercourse with a mentally handicapped person? Even if their legal guardian OK's it? Anyone know?

    I'm going to be doing to some digging, see if I can find this out.

  • L. (unregistered) in reply to Someone who's ego (or something...) is growing
    Someone who's ego (or something...) is growing:
    Maybe he could make the money by "renting out" the child in question. It's not like they would understand what was going on.

    Hmmm... That makes me wonder... is it legal to EVER engage in intercourse with a mentally handicapped person? Even if their legal guardian OK's it? Anyone know?

    I'm going to be doing to some digging, see if I can find this out.

    Well, as long as you're digging, find me a corpse or two, I'm getting horny from the talk here --

  • (cs) in reply to Greg
    Greg:
    Instead of multiple returns, I allow myself one goto (and ONLY one which is named the same and serves the same purpose in every function): goto _exit;

    The end of my functions look like this:

    ret = SUCCESS; _exit: // cleanup mem/FPs. .... return(ret);

    I don't have any arguments against this other than aesthetics. I just prefer blocks for handling that, as do most devs.

  • Someone who's ego (or something...) is growing (unregistered) in reply to L.
    L.:
    Someone who's ego (or something...) is growing:
    Maybe he could make the money by "renting out" the child in question. It's not like they would understand what was going on.

    Hmmm... That makes me wonder... is it legal to EVER engage in intercourse with a mentally handicapped person? Even if their legal guardian OK's it? Anyone know?

    I'm going to be doing to some digging, see if I can find this out.

    Well, as long as you're digging, find me a corpse or two, I'm getting horny from the talk here --
    I don't care for ones from the ground. I like them to still have eyes for me to gaze into and feel... close.

Leave a comment on “The Phantom Duo's ChangeWord”

Log In or post as a guest

Replying to comment #:

« Return to Article