• (cs) in reply to L.

    Agreed. There are very few situations where you need more than ten lines in a method (other than naked local variable declarations, for all you 4:3 screen users that put them on separate lines). The only exceptional situation I can think of is when you have to map complexThingA to complexThingB (e.g., anything with XML, OR-Mapping, factory pattern, etc., since you potentially need large switches).

    If you have loops more than two or perhaps three deep, it's time for some more classes.

    If I'm not doing a complex mapping, I expect each class to fit on one screen (with comments hidden). I tend to combine very closely-related lines of code on the same line to pull this off, such as setting properties from constructor parameters.

    Fitting almost all my classes on one screen really helps me "get" each class. But I'm a freak, so YMMV.

  • (cs) in reply to hoodaticus
    hoodaticus:
    Agreed. There are very few situations where you need more than ten lines in a method (other than naked local variable declarations, for all you 4:3 screen users that put them on separate lines). The only exceptional situation I can think of is when you have to map complexThingA to complexThingB (e.g., anything with XML, OR-Mapping, factory pattern, etc., since you potentially need large switches).

    If you have loops more than two or perhaps three deep, it's time for some more classes.

    If I'm not doing a complex mapping, I expect each class to fit on one screen (with comments hidden). I tend to combine very closely-related lines of code on the same line to pull this off, such as setting properties from constructor parameters.

    Fitting almost all my classes on one screen really helps me "get" each class. But I'm a freak, so YMMV.

    I must be a freak because that's how I likes it too...

    RE mapping between objects: I've done operator overloading (yes, I know it tightly couples the objects) to make the method cleaner, or even a generic helper which caches all the PropertyInfo in a dictionary so you can quickly do it in one place using reflection. This has come in really handy when dealing with DTOs, BOs and view models. If you're not a reflection fan, check out this link. I've done both, and put them in extension methods so you get code like this:

    var userDto = userBo.CopyTo<UserDTO>();
    BTW - I believe Jon Skeet (God) originally wrote the PropertyCopy, and other utils like this.

  • QJo (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    Agreed. There are very few situations where you need more than ten lines in a method (other than naked local variable declarations, for all you 4:3 screen users that put them on separate lines). The only exceptional situation I can think of is when you have to map complexThingA to complexThingB (e.g., anything with XML, OR-Mapping, factory pattern, etc., since you potentially need large switches).

    If you have loops more than two or perhaps three deep, it's time for some more classes.

    If I'm not doing a complex mapping, I expect each class to fit on one screen (with comments hidden). I tend to combine very closely-related lines of code on the same line to pull this off, such as setting properties from constructor parameters.

    Fitting almost all my classes on one screen really helps me "get" each class. But I'm a freak, so YMMV.

    I must be a freak because that's how I likes it too...

    RE mapping between objects: I've done operator overloading (yes, I know it tightly couples the objects) to make the method cleaner, or even a generic helper which caches all the PropertyInfo in a dictionary so you can quickly do it in one place using reflection. This has come in really handy when dealing with DTOs, BOs and view models. If you're not a reflection fan, check out this link. I've done both, and put them in extension methods so you get code like this:

    var userDto = userBo.CopyTo<UserDTO>();
    BTW - I believe Jon Skeet (God) originally wrote the PropertyCopy, and other utils like this.

    I can identify with this attitude - but only a little.

    I've worked with people who like everything on one screen themselves - but they were writing Fortran on a 80x24 screen. No matter how much I encouraged them to progress to the 20th century and utilise the functionality of their VT100 terminal emulator, i.e. expand it to 48, or even (gasp!) 72 lines, nobody took this suggestion on board. The excuse was "It makes it too small and impossible to read." The backatcha "But you're happy reading emails at that resolution, where's the problem?" never seemed to wash.

    Some of this may account for the fact that none of these Fortranites were offered the opportunity for training in other languages, e.g. java, c, html, SQL, xsl, jsp, etc. Then they wondered why they faced long-term unemployment when the company had to downsize.

  • (cs) in reply to L.
    L.:
    There's nothing that's 10 (real, not 867 character long) lines long AND unreadable ... well almost nothing.
    Thank you for saying "almost". Otherwise I was going to recommend that you give Perl a shot.

    I kid, I kid, Perl is great! :D

  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    RE mapping between objects: I've done operator overloading (yes, I know it tightly couples the objects) to make the method cleaner

    I do that too, for object => object conversions. Needless to say, it's the appropriate cast operator we're overloading (for the benefit of the audience).

    , or even a generic helper which caches all thePropertyInfo in a dictionary so you can quickly do it in one place using reflection.

    Yeah, you need to cache those PropertyInfos. I swear it's like we share the same brain.

  • (cs) in reply to boog
    boog:
    Otherwise I was going to recommend that you give Perl a shot.
    Zunesis? Are you awake?
  • (cs) in reply to hoodaticus
    hoodaticus:
    boog:
    Otherwise I was going to recommend that you give Perl a shot.
    Zunesis? Are you awake?
    He doesn't have class until later today. We'll have to wait.
  • incassum (unregistered) in reply to AssBlaster
    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.

    You don't know what you're talking about: people that insist on a single-return statement are stubborn and narrow-minded. In addition, it's easy to create logical errors with single-return statement in [longer] functions.

  • capio (unregistered) in reply to Sutherlands
    Sutherlands:
    Multiple returns are bad because people do this:
    void Function()
    {
       MyClassThatRequiresCleanup c = Initialize();
       if(someCondition) return;
       c.Cleanup();
    }
    
    Of course, you can get around that by using try/finally (most languages), using (C#), or by not being a bad programmer, but the "rules" were created when most of these things were not around.

    On the contrary, idiots write single-line if-content on the same line as the if. It's unreadable, and my mind first catches that "c.cleanup" to be what executes if that test returns false.

  • THE zunesis, as re... *yawn*... quested (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    boog:
    Otherwise I was going to recommend that you give Perl a shot.
    Zunesis? Are you awake?
    He doesn't have class until later today. We'll have to wait.
    Didn't fall asleep. Guess I came just in time.

    I spotted that one too, but I can't always think of how to squeeze something out of it. When you've been deep in this business for as long as I have, you get tired of picking all the low-hanging fruit.

    Anyways, I'm thinking of moving on. I'm thinking of starting a web comic that takes a hard look at current events. It'll have a cast of creative and thoughtful underdogs that rail against the injustice that pervades modern society. Maybe a strip will consist of our heroes at the NYSE giving out random hugs in order to engender caring for one's fellow man ("Gold... is cold, man!"). And then they all fuck each other.

  • (cs) in reply to THE zunesis, as re... *yawn*... quested
    THE zunesis:
    C-Octothorpe:
    hoodaticus:
    boog:
    Otherwise I was going to recommend that you give Perl a shot.
    Zunesis? Are you awake?
    He doesn't have class until later today. We'll have to wait.
    Didn't fall asleep. Guess I came just in time.

    I spotted that one too, but I can't always think of how to squeeze something out of it. When you've been deep in this business for as long as I have, you get tired of picking all the low-hanging fruit.

    Anyways, I'm thinking of moving on. I'm thinking of starting a web comic that takes a hard look at current events. It'll have a cast of creative and thoughtful underdogs that rail against the injustice that pervades modern society. Maybe a strip will consist of our heroes at the NYSE giving out random hugs in order to engender caring for one's fellow man ("Gold... is cold, man!"). And then they all fuck each other.

    Ah, so that's where anonymouse forum perverts go to retire...

  • (cs) in reply to capio
    capio:
    On the contrary, idiots write single-line if-content on the same line as the if. It's unreadable, and my mind first catches that "c.cleanup" to be what executes if that test returns false.
    LOL. I think the complete opposite for the exact same reasons. Using 3-4 lines of code for a one-line if, forcing closely-related code off the screen, is TRWTF.

    For that matter, I often do this:

    foreach(blah in blahSet) if (blah != null) blah.blegh();

    Which is just as clear as the 6-7 line version you would have, but I also get to see the entire class on the screen, which is VERY readable.

    Addendum (2011-08-12 12:41):

    But I'm just as likely to do:

    blahSet.ForEach<Blah>( b => { if (b!=null) b.blegh(); });
  • (cs) in reply to hoodaticus
    hoodaticus:
    For that matter, I often do this:

    foreach(blah in blahSet) if (blah != null) blah.blegh();

    Which is just as clear as the 6-7 line version you would have, but I also get to see the entire class on the screen, which is VERY readable.

    Addendum (2011-08-12 12:41):

    But I'm just as likely to do:

    blahSet.ForEach<Blah>( b => { if (b!=null) b.blegh(); });

    I'm going to have to strongly disagree with you about the first one because there's no "cue" for the readers eyes of where the code flows. Sure it makes sense to you because you wrote it. That being said, I like your second example because at least it groups each expression visually, though if it got one more level complex (i.e. ToArray()), I'd break it into seperate lines. An if without brackets is fine, but I still prefer to break it into two lines, except in the case of a short lambda.

    Just a quick question: do you shorten method and/or variable names to minimize screen usage?

  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.

    Addendum (2011-08-12 14:18): I wonder how you feel about this - taken from something I'm writing right now:

    [code]query.Result.Where<Order>(o => o.ShippedOn.Date == DateTime.Now.PriorDay()).ForEach<Order>(o => { /do stuff/ });

  • (cs) in reply to hoodaticus
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.
    Good man! I've seen it several times where the developer will have a method with six parameters, and the signature looks a little like this:
    CrtNewClnt(string a, string g, bool li)
    WTF?! Why the hell didn't you createParameterNamesThatAreHellaLongBecauseYouHaveIntelliSenseSoWhoCares!?
  • (cs) in reply to hoodaticus
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.

    Addendum (2011-08-12 14:18): I wonder how you feel about this - taken from something I'm writing right now:

    query.Result.Where<Order>(o => o.ShippedOn.Date == DateTime.Now.PriorDay()).ForEach<Order>(o => { /*do stuff*/ });
    I'd break it up a bit just to make it a little easier to read:

    query .Result .Where<Order>(o => o.ShippedOn.Date == DateTime.Now.PriorDay()) .ForEach<Order>(o => { /do stuff/ });

  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.

    Addendum (2011-08-12 14:18): I wonder how you feel about this - taken from something I'm writing right now:

    query.Result.Where<Order>(o => o.ShippedOn.Date == DateTime.Now.PriorDay()).ForEach<Order>(o => { /*do stuff*/ });
    I'd break it up a bit just to make it a little easier to read:

    query .Result .Where<Order>(o => o.ShippedOn.Date == DateTime.Now.PriorDay()) .ForEach<Order>(o => { /do stuff/ });

    It never occurred to me that I could line break on a dot operator (duh!). Thanks!

  • (cs) in reply to hoodaticus
    hoodaticus:
    It never occurred to me that I could line break on a dot operator (duh!). Thanks!
    No problem... I saw a fellow developer doing it about 2 years ago and thought it looked awsome. I find breaking on the . (dot) really makes it stand out.
  • Neil Ferguson (unregistered)
    class Done extends RuntimeException {}
    
    class MyClass
    {
      // Java goto?
      int myCleanFunction()
      {
        int ret = 0;
        try
        {
          boolean infactweredone = dothis();
          if (infactweredone)
            throw new Done();
          ret = 712; // well, why not?
          dothat();
          ret = 713; // naturally
          infactweredone = dotheotherthing();
          if (infactweredone)
            throw new Done();
          ret = 711; // bacause i say so
        } // only one brace!
        catch (Done done) {}
        catch (Exception e)
        {
          ohno();
          ret = -1;
        }
        finally
        {
          necessarycleanup();
          return ret;
        }
      }
    } // class MyClass
    
  • (cs) in reply to reductio ad ridiculum
    reductio ad ridiculum:
    hoodaticus:
    boog:
    AssBlaster Returns:
    I'm not saying multiple returns are ALWAYS bad, especially in an embedded system without {insert several unreasonable constraints here}.
    That's all well and good, but when are they bad? I'm not yet convinced they ever are.
    AssBlaster Returns:
    As to the guy who asked why are GOTOs bad...
    I must have missed the comment where the guy asked why GOTOs are bad.
    Mutliple returns are only bad when used by a psychotic code monkey in his ten page long methods with flow control lines jumping around all over like Nightcrawler after he shot the president in X-Men 2. The reason is because it's nigh-impossible to tell which path their shitty code took on its way to ruining your day.

    Developers blessed with The Gift should completely ignore that rule, since it tends to make crystal-clear, well-factored code even clearer, and you'll probably never need to mentally reverse-execute their code anyway.

    Yep, good answer.

    Ok class, here's an example. Many of us may remember learning in grade school that starting a sentence with a conjunction is "bad", and not to do it. We learned it then, and many of us still remember "the rule".

    But think of the target audience--beginners in grammar. Say an excited little boy is telling a story. And he wants to tell you about it. And he thinks it's really great. And he's writing it down. And it's just like when he talks. And so he adds the ands, and the buts. And...you get the idea.

    Now take a look at a good novelist. It's usually not too hard to find places where they used "And" or "But" at the beginning of the sentence. It makes sense, and it's fine.

    Using a conjunction at the start of a sentence can be good grammer. Using it appropriately requires more than a beginners skill. It's correct to tell beginners that the rule is "don't start w/ conjunctions". Intermediate writers can get away with it, but need to keep it in mind. Advanced writers use it appropriately to great effect.

    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.

    rar

    So, never start a sentence with a "goto", unless you're an experienced writer. Got it.

    Car analogy: Hands at 10 and 2 (or 9 and 3, or whatever the hell they're teaching nowadays).

  • Luiz Felipe (unregistered) in reply to AndyC
    AndyC:
    The advantage of a single return should be obvious when, as part of codebase maintainence, you're required to add another post condition to a function (maybe something has to be logged or whatever). Structuring methods with a single exit point shows code written with maintainence in mind.

    Which is not to say that some cases - particularly the immeadiate drop out for invalid parameters - are never appropriate, but it's the sign of good code when multiple returns are used sparingly.

    Or you can encapsulate the function.

    int doSomething(int param1, int param2) { //blah if x() return 1; //blah return 2 }

    then you need to log or run something after function end, you can do

    int doSomething(int param1, int param2) { int r = doSomethingCore(param1,param2) doAnotherThing(param1, param2); return r; }

    int doSomethingCore(int param1, int param2) { //blah if x() return 1; //blah return 2 }

  • Luiz Felipe (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.
    Good man! I've seen it several times where the developer will have a method with six parameters, and the signature looks a little like this:
    CrtNewClnt(string a, string g, bool li)
    WTF?! Why the hell didn't you createParameterNamesThatAreHellaLongBecauseYouHaveIntelliSenseSoWhoCares!?

    Cool, using very long parameter names, you dont ever need to comment the code, put the comment in name of things.

  • trtrwtf (unregistered) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.
    Good man! I've seen it several times where the developer will have a method with six parameters, and the signature looks a little like this:
    CrtNewClnt(string a, string g, bool li)
    WTF?! Why the hell didn't you createParameterNamesThatAreHellaLongBecauseYouHaveIntelliSenseSoWhoCares!?

    Like the man who preferred to communicate with the departed by means of a contented psychic, I prefer a happy medium.

    What about names that are long enough to communicate intent, but not so long that they have to be parsed. longSentencesWithoutSpacesOrPunctuationEvenIfTheyHaveInternalCapitalizationAreHardToReadDontYouThink = true.

    single-letter variables are fine for loop counters, anything else should be a word or two. If you need more than that, again, your method may be too complex.

  • (cs) in reply to Neil Ferguson
    Neil Ferguson:
    class Done extends RuntimeException {}
    

    class MyClass { // Java goto? int myCleanFunction() { int ret = 0; try { boolean infactweredone = dothis(); if (infactweredone) throw new Done(); ret = 712; // well, why not? dothat(); ret = 713; // naturally infactweredone = dotheotherthing(); if (infactweredone) throw new Done(); ret = 711; // bacause i say so } // only one brace! catch (Done done) {} catch (Exception e) { ohno(); ret = -1; } finally { necessarycleanup(); return ret; } } } // class MyClass

    You're a fucking pervert. But then you already know that. Yum.

  • (cs) in reply to trtrwtf
    trtrwtf:
    C-Octothorpe:
    hoodaticus:
    C-Octothorpe:
    Just a quick question: do you shorten method and/or variable names to minimize screen usage?
    Never.
    Good man! I've seen it several times where the developer will have a method with six parameters, and the signature looks a little like this:
    CrtNewClnt(string a, string g, bool li)
    WTF?! Why the hell didn't you createParameterNamesThatAreHellaLongBecauseYouHaveIntelliSenseSoWhoCares!?

    Like the man who preferred to communicate with the departed by means of a contented psychic, I prefer a happy medium.

    What about names that are long enough to communicate intent, but not so long that they have to be parsed. longSentencesWithoutSpacesOrPunctuationEvenIfTheyHaveInternalCapitalizationAreHardToReadDontYouThink = true.

    single-letter variables are fine for loop counters, anything else should be a word or two. If you need more than that, again, your method may be too complex.

    Yeah, loop counters don't count (since you only need two, or one per dimension on your array that you're looping through - any more gets more classes instead). I just didn't feel like going into my list of exceptions to the NO ABBREVIATIONS, which also includes:

    a) The instance parameter in an extension method, b) The only parameter in a private method, c) The only type parameter in a generic method/class, d) Lambdas, e) Truly open data format abbreviations like CSV and XML, but not DOC, XLS, JAR, et cetera. Not TXT because it's one extra letter to spell it out, f) Vernacular abbreviations like ID, g) When I've already used, in scope, the most appropriate variable name for a type, and I need a second one because I'm juggling or cache-swapping or something, I abbreviate the second variable, h) Event signatures (obviously).

    Unless a variable is absolutely private (not internal or protected), I also give it XML comments.

    Other than that, I follow every guideline recommended by Microsoft, from capitalization styles to asynchronous API design. Except I also prefix fields with , which is not really an MS recommendation but is pretty standard (that or m).

    I spend a hell of a lot of time coding to the API to make sure whoever comes behind me has an easy time. I'm not going to throw it all away on lazy/bad/proprietary style.

  • (cs) in reply to AndyC
    AndyC:
    Which is not to say that some cases - particularly the immeadiate drop out for invalid parameters - are never appropriate, but it's the sign of good code when multiple returns are used sparingly.
    Other than for immediate dropout if something fails, or in a catch, I pretty much never have multiple returns. But I don't create variables for the sole purpose of sacrificing them at the altar of structured programming, either. If it came between having another return or creating another variable and reorganizing my method, I would add a return.
  • (cs) in reply to C-Octothorpe
    C-Octothorpe:
    hoodaticus:
    foreach(blah in blahSet) if (blah != null) blah.blegh();
    Sure it makes sense to you because you wrote it.
    I think it's more than that - it has to do with the way my brain structures a statement like that. Foreach adds 0 complexity for me - it's like one of my brain's primitive instructions, call it SET_BASED_OP.

    So to my mind, this:

    foreach (Blah blah in BlahSet) if (blah != null) blah.Blegh();

    Is no more complex than this:

    if (blah != null) blah.Blegh();

    And it doesn't matter who writes it. You can nest the foreach down to infinity and, as long as the ifs are only null checks, I won't ever get lost.

    I think it has to do with all the DBA stuff I do. I am terribly used to conditional set-based operations like this:

    UPDATE invoices SET Exists = 1 WHERE Number IS NOT NULL

    Which has precisely as much complexity as:

    foreach (Invoice invoice in InvoiceSet) if (invoice != null) invoice.SetExists(1);
  • trtrwtf (unregistered) in reply to hoodaticus
    hoodaticus:
    I spend a hell of a lot of time coding to the API to make sure whoever comes behind me has an easy time. I'm not going to throw it all away on lazy/bad/proprietary style.

    TRWTF is.... um, actually, no, that's pretty good. Carry on.

  • needMoreFunctions (unregistered) in reply to Frank
    Frank:
    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.

    Single point of return isn't the problem. Assuming you must do things procedurally, sounds like code that should be decomposed into multiple functions. The function you're describing sounds monolithic, suffering from the lack of a clearly defined responsibility (see Single Responsibility Principle). Or poor design in general.

  • humble_coder (unregistered) in reply to fulton

    As I'm catching up on a few days of codeSOD, I read this comment and want to shout out: "Thanks for pointing this out!" Full ACK.

  • cappeca (unregistered) in reply to reductio ad ridiculum
    reductio ad ridiculum:
    Using a conjunction at the start of a sentence can be good grammer. Using it appropriately requires more than a beginners skill. It's correct to tell beginners that the rule is "don't start w/ conjunctions". Intermediate writers can get away with it, but need to keep it in mind. Advanced writers use it appropriately to great effect.

    And remember, prepositions are something you never end a sentence with.

  • nisl (unregistered) in reply to bye
    bye:
    Frank:
    AssBlaster:
    Multiple return points are bad...
    ...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 early Atari BASIC interpreter was written for the 6502 processor which uses 2 bytes for a short-jump instruction (jump, howfar) but 3 bytes to return from a subroutine call. Since howfar is one byte, it can tell the processor to move to any of 255 locations, from -127 to +128, not counting zero for reasons left as an exercise for the reader.

    So anyway, if you're in the middle of a subroutine and you want to return, you can use 3 bytes to return or 2 bytes to jump to the end of the subroutine and piggyback onto its return instruction.

    If you have several small subroutines all packed into one consecutive 256 byte space, they can all share a single return instruction, with the other subroutines using jumps to exit.

    The mad geniuses who programmed Atari BASIC made generous use of this technique, saving dozens of bytes in total. And they had to, because by the time it was done there were (as I recall) only about 7 leftover unused bytes from the memory allocated to things like this.

    I'm sure you have that backwards. RET does not take parameters, so it should use fewer bytes than JMP.

    When the last thing a subroutine did was to call another subroutine, then you could save bytes and cycles by using JUMP instead of CALL followed by RET.

  • Spudd86 (unregistered) in reply to Duke
    Duke:
    If there's one redeeming quality in Java, it's that you can't do half of the things suggested in this wtf.

    Yes you can... you just have to make copies of the string, thereby making the code even worse, and it wouldn't even look all that different.

  • Spudd86 (unregistered) in reply to An Old Hacker
    Meh:
    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...

    No it isn't, at least not on most platforms, in C return is implemented in whatever way makes sense for the ABI, and often that means drop the return value in a specific register and execute the 'ret' instruction. (There may also need to be stuff to restore callee saved registers that have been used, and possibly restoring the old stack pointer and frame pointer if the ret instruction doesn't do that and they have changed).

    Also why would it be sad? It makes sense if the function epilog is long since it results in smaller code, in any case as a C programmer you don't need to care.

  • Spudd86 (unregistered) in reply to AA
    AA:
    A Young Hacker:
    I would be very surprised if compilers like GCC or LLVM implemented it using [i]jmp[\i] to have a single "return point"

    If your language has scoping rules such that there's some pretty significant cleanup to be done when returning from a function (running destructors and such), then it's actually pretty likely for a compiler to have that cleanup code in there once and jump to it for every other return, instead of duplicating it for every single point of exit.

    C is decidedly not one of those languages

  • Spudd86 (unregistered) in reply to Jibble
    Jibble:
    Frank:
    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.

    On every compiler I've used in the last ten years no extra code is executed unless an exception is actually thrown.

    Except frequently that stack unwinding code isn't terribly fast because the assumption is that it doesn't run very often, and it may need to do quite a bit of work to figure out what stuff it actually needs to clean up since optimization tends to obscure that sort of information. Since you are making assumptions about what optimizations exist anyway you might as well assume the compiler can do a tail call optimization and write your function to be easy to analyze for that, you'll get clearer code.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    There are no unbreakable rules, not even this one.
    But there are unbreakable principles, like this one.

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

Log In or post as a guest

Replying to comment #:

« Return to Article