Slashdot Mirror


Beautiful Code Interview

An anonymous reader writes "Safari Books Online has just posted an interview with Andy Oram and Greg Wilson, the two editors who put together the recent O'Reilly book, Beautiful Code. "Beautiful Code" features 33 different case studies about challenging coding scenarios from some of today's most high-profile developers and OS project leaders. There's also a new Beautiful Code web site based on the book where many of the authors are blogging about their work and coding practices."

286 comments

  1. Nothing to see here by AuMatar · · Score: 4, Funny

    Yeah, thats about the amount of beautiful code I expect to see in my life time.

    --
    I still have more fans than freaks. WTF is wrong with you people?
    1. Re:Nothing to see here by morgan_greywolf · · Score: 5, Funny

      "If builders built buildings the way programmers write programs, then the first woodpecker that came along would destroy civilization." -- forgot who said it.

    2. Re:Nothing to see here by larry+bagina · · Score: 5, Funny

      If it's any consolation, you did get the coveted first typo.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    3. Re:Nothing to see here by choongiri · · Score: 1

      Incorrect. First post also got first typo. But I guess that's what you get when you post quickly. Not that it makes any difference to me - I doubt I'll be able to type fast enough in my lifetime to get a first post anyway.

    4. Re:Nothing to see here by Anonymous+Brave+Guy · · Score: 2, Funny

      If we built our cars like we build our software, they would look great, they would have controls even a five-year-old could use, and every 65,536 miles they'd teleport you back to where you started.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    5. Re:Nothing to see here by tutwabee · · Score: 1

      Damn... why isn't there a +1 Ooh Burn! mod?

  2. hypocritter? by Anonymous Coward · · Score: 1, Informative

    I find it amusing that TFA has tons of html errors.

    1. Re:hypocritter? by Anonymous Coward · · Score: 1

      When I saw the subject of your comment I just envisioned very small hpipos running around bumping into each other on a linoleum floor.

    2. Re:hypocritter? by Anonymous Coward · · Score: 0

      Jeez, that's embarrassing.

      If that page were served with a MIME-type of application/xhtml+xml it wouldn't render at all.

  3. This just reminds me of my friend. by Anonymous Coward · · Score: 5, Funny

    His introduction to C++ teacher told him throughout the class that his code was not "pretty" because he wasn't properly commenting. The code always worked flawlessly, but still she marked "-1 code not pretty"
    On the final project he spent a good portion of time properly commenting all of his code and ended with a commented ascii flower and the following:

    //Look at my flower,
    //my pretty pretty flower.
    //Now my code is pretty

    He was marked off "-1 Sarcasm not appreciated"

    1. Re:This just reminds me of my friend. by morgan_greywolf · · Score: 2, Funny

      And to think if he posted it on Slashdot, he might've actually gotten a +5 Funny! ;)

    2. Re:This just reminds me of my friend. by mrchaotica · · Score: 4, Funny

      He should have removed one syllable from the last line; then he would have gotten "+1 haiku!"

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    3. Re:This just reminds me of my friend. by Mewtwo · · Score: 1

      If that actually ended up adversely affecting his grade, I'd say it's lawsuit time.

      --
      09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 SU CK IT MP AA
    4. Re:This just reminds me of my friend. by fractoid · · Score: 1

      My network programming lecturer had a physical network simulator package that we used, that would preprocess our C code and emit compile errors if we had certain misspellings in comments. That was awesome. :P

      On the other hand, our first year Java lecturer insisted that K&R was the One and Only Correct Brace Placement Style and marked us down if we used ANSI C++ style brace placement instead of K&R. 'Tard.

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    5. Re:This just reminds me of my friend. by Anonymous Coward · · Score: 0

      MY computer architecture/assembly language instructor (worked for various intelligence agencies, optimized lots of commercial satellite code) would visually SCAN at a 3-4 page 80x86 assembly program and spot MINOR errors *instantly*. He was faster than TASM in some things. We feared him..

      0_0

    6. Re:This just reminds me of my friend. by dargaud · · Score: 2, Interesting

      I've seen plenty of haikus over the years and read the wikipedia entry about them, but something escapes me entirely: what makes a haiku 'pretty' (or anything other than a complete waste of time by both the writer and the readers) ?!? For me it's just a bunch of text put in an arbitrarily hard to read configuration.

      --
      Non-Linux Penguins ?
    7. Re:This just reminds me of my friend. by SlashDread · · Score: 1

      One can argue that all art is a waste of time. I wont.

    8. Re:This just reminds me of my friend. by FuzzyDaddy · · Score: 2, Insightful

      No - the lesson is that it's worth not taking your grade so seriously that you muzzle yourself. As it often is in real life, sometimes you pay a price for being a smartass, but it's often worth it anyway.

      --
      It's not wasting time, I'm educating myself.
    9. Re:This just reminds me of my friend. by Anonymous Coward · · Score: 0

      You have just made the first step on the path to wisdom.

    10. Re:This just reminds me of my friend. by AgentBif · · Score: 2, Informative

      I think to many, part of the beauty of a remarkable haiku is the skill of the writer in packing big, powerful ideas or images into very few words. The haiku form is especially challenging because you have so little space to work with. It is wordcraft... and good wordcraft takes a lot of skill and effort.

      In a way, it's like appreciating a remarkable skateboard trick or an amazing touchdown catch because not everyone has the skill to do those things, especially the outstanding examples.

      --
      Privacy Statement: We value your privacy! It is very valuable. That's why we try to sell it whenever we can.
    11. Re:This just reminds me of my friend. by zolaar · · Score: 1

      Do you have to take the null terminator into account when doing haikus in C ?

      --
      One man's constant is another man's variable.
    12. Re:This just reminds me of my friend. by aproposofwhat · · Score: 1

      This simple small (null)
      Haiku requires no more (null)
      Termination (null)

      --
      One swallow does not a fellatrix make
    13. Re:This just reminds me of my friend. by stdarg · · Score: 3, Interesting
      If you put a sentence in haiku form, it's probably not going to be pretty. Just like most "free verse" poetry often looks like
      the person just
      gave
      up
      and decided to
      B R EA K!
      the lines arbitrarily.

      Oh how dramatic. Likewise, you can't say

      My car had a flat
      tire, so I called around for
      quotes for some new tires

      and call it haiku. Well I suppose you could, but it's awful. Here's one I just found that I like:

              * I kill an ant
              * and realize my three children
              * have been watching.

      It describes a brief moment but it captures many levels of feeling. Because it's just sitting there by itself without a surrounding story, it's more forceful and clear. You can pause and think about it. If it were a line from a short story or longer poem, the subsequent lines would probably either insult your intelligence by spelling out the implications, or distract from it by moving on to a different subject. Also, as hard as it is to believe, I thought the 3 line form actually helped this haiku. When I read the first line, I half expected it to be a funny or sarcastic haiku because killing an ant is such a small thing. Then the second line introduces his children, but I still didn't see it coming that they were watching until the third line. Each line introduced a different feeling to me (humor, tension, then sadness) which makes it a very successful haiku, I think.

      There's a funny story told by Herodotus about the Spartans (http://www.greektexts.com/library/Herodotus/Thali a/eng/59.html second paragraph), which I'll quote:

      When the banished Samians reached Sparta, they had audience of the
      magistrates, before whom they made a long speech, as was natural
      with persons greatly in want of aid. Accordingly at this first sitting
      the Spartans answered them that they had forgotten the first half of
      their speech, and could make nothing of the remainder. Afterwards
      the Samians had another audience, whereat they simply said, showing
      a bag which they had brought with them, "The bag wants flour." The
      Spartans answered that they did not need to have said "the bag"

      I quote it to illustrate that some people just enjoy making a puzzle of how to express meaning in as few words as possible. If you find that story as funny as I do, then you may like haikus after all (if you find the right ones that are actually good).

      Note that my rather long-winded writing style means that I am incapable of writing good haikus myself. :)
    14. Re:This just reminds me of my friend. by mrchaotica · · Score: 1

      On the other hand, our first year Java lecturer insisted that K&R was the One and Only Correct Brace Placement Style and marked us down if we used ANSI C++ style brace placement instead of K&R. 'Tard.

      Both you and he need to discover a little piece of software called indent.

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    15. Re:This just reminds me of my friend. by dargaud · · Score: 1

      Thanks for trying. Excellent classic greek story. And I get your point about your haiku being readable on several different levels. I guess I'm just impervious to poetry after being tortured with too much of it at school...

      --
      Non-Linux Penguins ?
  4. The OpenBSD code is studly. by Anonymous Coward · · Score: 3, Informative

    If you haven't looked at it already, you should glance through the OpenBSD source code. It's truly remarkable how well-written it is. But I wouldn't consider it "beautiful". I think studly is a better word. It's rugged, strong, and built to handle the toughest of the tough.

    1. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 3, Informative
      You know.. I've run across a particular bug in the OpenBSD source code on at least two occasions. Specifically, NULL is being treated as a null character.

      Now, there's some bit of wiggle room for OpenBSD, since NULL can be either:

      #define NULL 0
      or

      #define NULL ((void*)0)
      (or something equivalent, like 0L, etc).

      Anyway, I presume OpenBSD uses the first definition, because otherwise a diagnostic is required when void* is assigned to a char. If NULL is defined as 0, an unfortunate coincidence allows it to be assigned to chars, since 0 is the null byte.

      However, it's still bad code. It's not portable (which OpenBSD might not care about), but it represents an ignorance of the language. There's really no reason to do something in a non-portable manner when it's just as easy to do it portably; who knows, perhaps in the future OpenBSD's C library maintainer will realize that defining NULL to be (void*)0 has advantages and the application will not build; or at least not build without diagnostics.

      If the OpenBSD developers like using a macro instead of an unadorned zero, it's easy enough to make one yourself. Though many people find '\0' to be sufficiently self-documenting, much in the way that writing NULL is self-documenting, when you compare it with writing a zero.

      In short:

      char *pointer = NULL; /* Portable, self-documenting */
      char *pointer = 0; /* Portable, perhaps not as self-documenting */
      char character = '\0'; /* Portable, self-documenting */
      char character = 0; /* Portable, perhaps not as self-documenting */
      char character = NULL; /* NOT portable! Try with GNU C library 2.5 (probably other versions too) */
      (the comments would line up nicely if I knew anything about HTML)

      gcc will whine about a conversion without a cast on the last one; that doesn't mean a cast is the way to fix it, though! Odds are it will work but there's no guarantee and it's just not pretty, especially when both of the examples above it are legal.

      If you want to see this bug in OpenBSD, check src/usr.bin/cvs/history.c.

      I have no desire to report the bug to OpenBSD, because there appears to be a much better than even chance that the reply will be hostile and childish.
    2. Re:The OpenBSD code is studly. by garett_spencley · · Score: 4, Funny

      Hey Theo ... haven't chatted with you in a while. How's it going ? Family doing well ?

    3. Re:The OpenBSD code is studly. by dextromulous · · Score: 1

      char character = NULL; /* NOT portable! Try with GNU C library 2.5 (probably other versions too) */

      True. AFAIK this code is not meant to be portable to other libraries or operating systems which is why it is in the OpenBSD CVS (they maintain the code in their CVS repositories.)

      --
      There are two types of people in the world: those who divide people into two types and those who don't.
    4. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 1, Funny

      Fixed, thanks for the report!

    5. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 0

      Given that you think '\0', NULL and 0 are the same thing I don't think your opinion of OpenBSD coding practices is particularly valid.

    6. Re:The OpenBSD code is studly. by teknopurge · · Score: 1

      Please mod parent up and GP down to hades.

      '\0' is NULL in every OS that uses null-terminated strings I have ever encountered.

    7. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 0

      That should be -1 troll.

    8. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 0

      OpenBSD is one of the most portable systems around, jackass. At least read up on what you're inanely bitching about.

    9. Re:The OpenBSD code is studly. by Anonymous Coward · · Score: 0

      They are ALL integer constants that evaluate to 0, moron.

    10. Re:The OpenBSD code is studly. by MetalOne · · Score: 1

      Out of curiosity I had to see how Windows defines it.
      The following is in windef.h
      #ifndef NULL
      #ifdef __cplusplus
      #define NULL 0
      #else
      #define NULL ((void *)0)
      #endif
      #endif

  5. People hate my gotos by jimmyhat3939 · · Score: 2, Insightful

    But I find goto is often as beautiful as it gets:

    for (loop 1) {
          for (loop 2) {
                if (something happens that makes me want to bail on both loops) {
                      goto loop_done;
                }
                do_inner_loop_work;
          }
    }

    loop_done:

    --
    Free Conference Call -- No Spam, High Quality
    1. Re:People hate my gotos by morgan_greywolf · · Score: 1, Informative

      Um, ahem. You might want to take a look at a while { } loop instead

    2. Re:People hate my gotos by morgan_greywolf · · Score: 2, Interesting

      IOW, for those that need visuals:

      i=0;
      while (not condition that makes me want to bail) {
                      j=0;
                      while (not condition that makes want to bail) {
                                        inner loop
                      }
                      outer loop
                      i++
      }

    3. Re:People hate my gotos by jbellis · · Score: 1

      fortunately newer languages solve this with labeled loops and break and continue ; no goto needed.

    4. Re:People hate my gotos by morgan_greywolf · · Score: 1

      oops. Need a j++ after 'inner loop'

    5. Re:People hate my gotos by Anonymous Coward · · Score: 0

      In JavaScript you can use labels:

      outer:
      for (loop 1) {
            inner:
            for (loop 2) {
                  if (something happens that makes me want to bail on both loops) {
                        break outer;
                  }
                  do_inner_loop_work;
            }
      }

      Posting as AC for obvious reasons :)

    6. Re:People hate my gotos by jimmyhat3939 · · Score: 3, Insightful

      Personally, I think that is uglier than goto. Also, I think it's more confusing, because you have this condition repeated twice, and you'd have to have a "break;" in the right spot in the inner loop, as well as some sort of a condition check right after you get out of the inner while loop to ensure the remainder of the outer while loop does not execute once the condition is met. Yes, you can do this a lot of different ways, but you have to torture the while/for syntax to avoid goto.

      --
      Free Conference Call -- No Spam, High Quality
    7. Re:People hate my gotos by Anonymous Coward · · Score: 1, Informative
      Dude, those are gotos in disguise.

      label:
      for(;;)
      { //...

            if(condition)
            {
                  break label;
            } //...
      }


      or

      label:
      for(;;)
      { //...

            if(condition)
            {
                  continue label;
            } //...
      }


      is the same as

      label:
      for(;;)
      { //...

            if(condition)
            {
                  goto label;
            } //...
      }


      So as you can see, there really isn't anything special about the labeled break statement you find in a language like Java. It's essentially just a C-style goto, but invoked without using a "goto" keyword. That helps make it acceptable to those who don't see the goto as the tool that it is, but instead see it as some kind of monstrosity (when it isn't).

    8. Re:People hate my gotos by RootsLINUX · · Score: 1, Insightful

      How about this as an alternative:

      bool continue_loop = true;
      for (loop1 && continue_loop) {
            for (loop2) {
                  if (termination condition == true) {
                          continue_loop = false;
                          break;
                  }
                  do_inner_loop_work();
            }
      }


      --
      Hero of Allacrost, a FOSS RPG for *NIX/*BSD/OS X/Win
    9. Re:People hate my gotos by morgan_greywolf · · Score: 1

      What's beautiful code? Beauty is in the eye of the beholder. Personally, I think all instances of goto are ugly. But, then again, I grew up in the days when every kid with a BASIC interpreter thought he was a 'programmer'. I remember horrible, horrrible spaghetti code that used lots and lots of GOTOs. Hell, i even wrote a bunch of code like that. *shudder*

      While I do think that the OPs example isn't spaghetti code, the appearance of goto makes me want to wretch.

    10. Re:People hate my gotos by Anonymous Coward · · Score: 0

      retch, even.

    11. Re:People hate my gotos by poot_rootbeer · · Score: 1

      fortunately newer languages solve this with labeled loops and break and continue ; no goto needed.

      0x05 dollars says that "break (loop-label)" and "goto (post-loop-label)" compile to almost identical opcodes.

    12. Re:People hate my gotos by DuckWizard · · Score: 1

      Don't you know that there is no circumstance under which use of goto is acceptable?

      Similarly, I propose that JMP should be removed from every instruction set, because it is too much like goto and therefore is pure evil.

    13. Re:People hate my gotos by Anonymous Coward · · Score: 0

      Java also.
      Also posting as AC for obvious reasons :)

    14. Re:People hate my gotos by Breakfast+Pants · · Score: 1

      j++;

      --

      --

      WHO ATE MY BREAKFAST PANTS?
    15. Re:People hate my gotos by garett_spencley · · Score: 2, Interesting

      Exactly. Loop breaking is just one of the most popular justifications for using goto. Solving nested loop breaking alone is an attempt to please both camps by saying "ok so there are *some* times where using goto makes sense but we were taught from the time we were still in diapers that you must NEVER use goto so we'll just fix that by applying a band-aid".

      Goto has been a feature of almost every programming language for a reason. It is useful. If it weren't useful then nobody would ever use it and then we could strip it from languages and no one would complain because no one ever used it to begin with because it's useless and "dangerous".

      I know what I'm about to say next is cliche but try grepping for goto in the Linux kernel source.

      Just because some n00bs liked to write nightmarish spaghetti-code BASIC programs 20 - 30 years ago with millinos of gotos thus inspiring CS profs everywhere to threaten beating their students with paddles if they used a single goto does not mean that it's useless, evil or "dangerous". Any crap programmer can write messy spaghetti code with or without a goto.

      Of course, by the same logic, coming up with better ways to do things is at the heart of everything technology. But I'm not convinced that adding in control structures to break out of nested loops is any better than just using a goto. It seems to me like these languages are trying to find a way to eventually get goto out of them (or they don't have goto to begin with and are now trying to make up for it's absence because they've started to realize is useful after all).

    16. Re:People hate my gotos by garett_spencley · · Score: 5, Interesting

      Any crap programmer can write spaghetti code with or without the use of 'goto'.

      If goto were not useful or necessary then languages would have dropped it years ago when CS profs started to dread it because they couldn't teach their students properly and got tired of spitting out idiot programmer after idiot programmer who tortured them with goto-ridden spaghetti code.

      Telling people to NEVER use goto is like saying "never use a chainsaw because if you attempt to cut down a weed you'll just end up with a big mess". So what, we use a hand saw to cut down an oak tree ? There are far more elegant solutions for a lot of things that can be accomplished with goto. Conversely, there are occasions where goto makes for a more elegant solution.

      At the very least, as you put it "beauty is in the eye of the beholder". Using your own philosphy I opt for giving programmers all of the necessary tools that they may find useful, and deciding for themselves which ones to use. After all, there are some programmers out there who could write code that is 100 x more efficient and elegant using ONLY gotos in C with main as the only function than I ever could using goto-free, well designed and thought-out object oriented Java, for example.

      No matter what you do, the end result will always be the same anyway. Exceptional programmers will continue to produce exceptional code and pasta chefs will continue to produce spaghetti.

    17. Re:People hate my gotos by Ekarderif · · Score: 1

      return_val func(needed_variables) {
          for(loop 1) {
              for(loop 2) {
                  if(something_requires_breaking_out) {
                      return relevant_information;
                  }
              }
       
              do_inner_loop_work;
          }
      }
      Simple isn't beautiful. goto is never beautiful.
    18. Re:People hate my gotos by Anonymous Coward · · Score: 0

      The whole thing should be inside a function:

      function foo() {
          for (loop 1) {
                      for (loop 2) {
                                  if (something happens that makes me want to bail on both loops) {
                                          return;
                                  }
                                  do_inner_loop_work;
                      }
          }
      }

      no goto, same structure, nicer all round: best of both worlds.

    19. Re:People hate my gotos by Anonymous Coward · · Score: 0

      What the fuck are you talking about? Simple code is usually not only beautiful, it's also usually efficient, easily-maintained, and quicker to write correctly.

      Maybe it makes your ego feel really big when you write some convoluted monstrosity in Java. But for those of us who are in the real world, where we have to deal with scalability and maintainability, we tend to consider people like you to be fools.

    20. Re:People hate my gotos by ben_rh · · Score: 3, Informative

      That's still better as a for { } loop. Apart from it's concise variable initialisation and post-loop statement, for is while.

      for (i = 0; not bail_condition; i++) {
          for (j = 0; not bail_condition; j++) {
              inner loop
          }
          outer loop
      }

    21. Re:People hate my gotos by Ekarderif · · Score: 1

      Simple is not synonymous with beautiful, and it never will be. Good code is beautiful but not necessarily simple. If your head wasn't up your ass, you'd realize this immediately.

    22. Re:People hate my gotos by ozzee · · Score: 1

      Any crap programmer can write spaghetti code with or without the use of 'goto'.

      translates to:

      "I can write bad code in any language!"

      ... which is one of my fav. responses to language wars.

    23. Re:People hate my gotos by Jaime2 · · Score: 2, Informative

      I think part of the problem might be that compilers have a hard time figuring out gotos. GOTO doesn't imply any scope transition and the compiler has to figure it out. However, BREAK is very clear on which scope is being abandoned. Also, a goto will always compile (well, it depends on the language), but a break with a label will only compile if used in a sane manner.

      BTW, I met a guy whose biggest dissapointment with VB.Net was that they did away with GOSUB. I shot him.

    24. Re:People hate my gotos by Crispy+Critters · · Score: 3, Insightful
      So what if they compile to the same code? Source code is for humans to read, and machine code is for machines to read. Comments don't show up in the compiled code at all. Does this mean that they serve no purpose?

      Break's and goto's are very different, and I am surprised to see so many people say that they are essentially the same. When I am reading code and I see a break statement, I know where the flow goes. When I see a goto statement, I have no idea where the flow goes unless the label is withing a few lines. That is the difference.

    25. Re:People hate my gotos by urbanRealist · · Score: 1

      do_work(){
              for (loop 1) {
                          for (loop 2) {
                                      if (something happens that makes me want to bail on both loops) {
                                                  loop_done();
                                                  return;
                                      }
                                      do_inner_loop_work;
                          }
              }
      }

      loop_done(){
              loop_done;
      }

      --
      I've seen a lot of things, but I've never been a witness.
    26. Re:People hate my gotos by compro01 · · Score: 2, Insightful

      simple code is always beautiful, but beautiful code isn't always simple.

      --
      upon the advice of my lawyer, i have no sig at this time
    27. Re:People hate my gotos by locster · · Score: 1

      It drives me crazy the number of coders who still, in 2007, have a bee in their bonnet about goto statements (they're just evil apparently) or return statments in the middle of a function body - often prefering the alternative of umpteen nested if statements indented right off the the screen. I remember rolling my eyes when being taught these sorts of rules at university, the thought that some people actually took them seriously and are still using them years later just shows how willing some people are to blindly follow rules without question. I guess that's what distinguishes a code monkey from a coder?

    28. Re:People hate my gotos by a.d.trick · · Score: 1

      ever thought of using functions and a return?

    29. Re:People hate my gotos by gd2shoe · · Score: 1

      Sorry, I can't help but point out that for, while, do, case, break, etc. all use a jump instruction. In essence, they all rely on goto. What makes these special is that they are designed to make it hard to write nonsense code. In that respect, label breaks are perfectly legitimate control flow elements NOT equivalent to goto (as they are controlled and specific meaning).

      --
      I won't join Slashcott. OTOH, If Beta goes live, I just won't be back until it's fixed. Sorry Dice.
    30. Re:People hate my gotos by Tablizer · · Score: 1

      fortunately newer languages solve this with labeled loops and break {label} and continue {label}; no goto needed.

      Yes, but that just complicates the language and is almost goto-ish itself. Goto's like the original example are not really a bad thing because there is only one. If there were dozens, then I might panic. A single well-placed goto is not evil.

    31. Re:People hate my gotos by Ungrounded+Lightning · · Score: 1

      Don't you know that there is no circumstance under which use of goto is acceptable?

      Only if you raise structured programming to the status of a religion.

      Gotos tend to cause problems by tying code into incomprehensible (and thus undebuggable) knots. The main battle in programming is to limit the scope you must think about simultaneously to the cardinality of your short-term memory. Gotos tend to suck in side-effects from all over the place and create a mental overflow.

      Limiting yourself to concatenation, alternation, and iteration does a fine job of limiting the scope you must think about to the capacity of a human mind. But it does have a cost: It doesn't gracefully handle error escapes from deep nesting. Gotos handle that VERY well, while shoehorning error escapes in via conditionals and the like pollutes the code in the intermediate levels with information properly the subject of just the endpoints of the escape.

      So IMHO goto has exactly one proper place in programming: Graceful error escape from deep nesting.

      (Of course a goto escape doesn't handle the side-effects on the intermediate levels of code. Which is why object-oriented languages encapsulate these into the construction and destruction of local objects and do error escape with first-class constructs like catch/throw, which lets the compiler and programmer conspire to insure that intermediate-level cleanup is properly handled on the way out.)

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    32. Re:People hate my gotos by Ungrounded+Lightning · · Score: 1

      no goto, same structure, nicer all round: best of both worlds.

      Adds function overhead (which the compiler may not be able to optimize away).

      May require ugly return value status coding.

      Error escapes from multiple depths can require additional layers of functions.

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    33. Re:People hate my gotos by gfody · · Score: 2, Insightful

      0x05 dollars says that "break (loop-label)" and "goto (post-loop-label)" compile to almost identical opcodes.


      Indeed. As does "for", "while", "repeat" or whatever else your HLL gives you.
      --

      bite my glorious golden ass.
    34. Re:People hate my gotos by Estanislao+Mart�nez · · Score: 1

      It drives me crazy the number of coders who still, in 2007, have a bee in their bonnet about goto statements (they're just evil apparently) or return statments in the middle of a function body - often prefering the alternative of umpteen nested if statements indented right off the the screen.

      Return statements in the middle of the a function body are usually a good signal of bad code; they make the flow of the code more obscure. However, they usually come hand in hand with a clearer signal: functions that are too long.

      Spend a couple of months programming in a language like Scheme, where there is no return statement, and you'll see what I mean; the logic of the code is much more evident.

    35. Re:People hate my gotos by Anonymous Coward · · Score: 0

      I would say that the difference between exceptional programmers and pasta chefs is the ability to see the whole problem they are trying to solve, and properly apply principles of code reuse and code efficiency. Couple this with the ability to make said code readable and easily understandable (where applicable), and you have an exceptional coder. This applies to programmers of every language of every paradigm.

    36. Re:People hate my gotos by Anonymous Coward · · Score: 0

      Not to disagree with you, but I still like C a lot, except these days I can't tell how much control I have with the fancy compilers/CPU/microcode tricks. Yeah, so I'm in agreement here.

      (Still doing some C work however - nothing so cross-platform exist yet)

    37. Re:People hate my gotos by Plutonite · · Score: 1

      Your goto can provide minimalist, computationally efficient and indeed pretty code, but it can also cause disasters. When writing big applications with hundreds of developers, it is difficult to coordinate/enforce proper usage of goto (which is really just a JMP instruction in the end) as you have done here, and avoid disastrous spaghetti code that jumps back and forth into snippets, making it a nightmare to trace, mathematically prove, or maintain.

      You may think that things like break + a boolean flag might be less efficient, but with "break" your program counter always ends up right outside the iterative loop scope, whereas a goto JESUS_CHRIST_BAD_SHITE_HAPPENING is not always necessarily placed correctly and is arguably less meaningful/understandable. Standards are nice things - try to standardize good goto usage and you end up with something a lot like a break + check + break scenario to get out of nested statements.

    38. Re:People hate my gotos by matvei · · Score: 1

      If you can factor the loop into its own function, you can replace the goto with a return to please the "I read somewhere that gotos must never be used" folks. :-)

      Seriously though, IMHO gotos should be used just like that -- to handle function-local exception conditions. Gotos should be avoided when they make code hard to follow, but why avoid them when they make the code easier to read? On the other hand, "open classes" as Ruby calls them -- *cough*COMEFROM*cough* -- they are pure evil. ;-)

    39. Re:People hate my gotos by russellh · · Score: 1

      So IMHO goto has exactly one proper place in programming: Graceful error escape from deep nesting.
      Computers do just fine with spaghetti code. it's the humans that don't. Structured programming is one way to make it easier for people to write and understand programs, by severely limiting the kinds of software structures you are allowed to create. But I'm sure there are other, less restrictive ways waiting to be invented. I hold out hope that nested boxes isn't the be-all, end-all of programming.
      --
      must... stay... awake...
    40. Re:People hate my gotos by chromatic · · Score: 1

      When writing big applications with hundreds of developers, it is difficult....

      Heh. You can safely end that sentence right there.

    41. Re:People hate my gotos by syousef · · Score: 1

      If you have a good REASON to use GOTO, yeah okay.

      However just because there are programmer who can use it well, doesn't mean that they will, or that there aren't plenty more who can't use it to save their life. It takes expertise, and it's still usually harder to code that does things by jumping around.

      To use your own analogy if you were teaching people to cut weeds, you'd never start with the damn chainsaw. You'd teach them to cut weeds and when they were proficient progress them to bringing down trees with a chainsaw.

      --
      These posts express my own personal views, not those of my employer
    42. Re:People hate my gotos by Anonymous Coward · · Score: 0

      Congratulations!
      You made the code more complex and less clear.

    43. Re:People hate my gotos by someone1234 · · Score: 1

      Sometimes i just move that double for into a new function, and use return from the inner loop. Yeah, it is cheating, but usually fools the suckers that review my code.

      --
      Patents Drive Free Software as Hurricanes Drive Construction Industry
    44. Re:People hate my gotos by bytesex · · Score: 1

      Just wrap them up inside a function and 'return' from it, instead of goto-ing to the end.

      --
      Religion is what happens when nature strikes and groupthink goes wrong.
    45. Re:People hate my gotos by locster · · Score: 1

      They /can/ be a signal for bad code, but they /can/ make certain types of code much clearer, e.g. iy you have a long list of test cases that you wish to test in turn - exiting any one if it fails. I guess my point is that some coders just apply these hard rules they learned without really thinking about why the rules exists and therefore where it may not apply.

    46. Re:People hate my gotos by Anonymous Coward · · Score: 0

      int func( int foo, char *bar )
      {
        if( foo < 42 )
          return -EINVAL;

        if( !bar )
          return -ESRCH;

        /* do stuff */

        return 0;
      }

    47. Re:People hate my gotos by pAnkRat · · Score: 1

      How about throwing an BreakOutOfAllLoopsException in the inner loop.
      Just don't forget to catch the exception in the apropriate place.

      --
      we need an "-1 Plain wrong" moderation option!
    48. Re:People hate my gotos by stormeru · · Score: 0

      Hey! I write spaghetti code when I'm hungry.
      Now where's that fscking phone number from the Italian food delivery service?

    49. Re:People hate my gotos by Bill+Dog · · Score: 2, Interesting

      He said in the middle. Some sanity checks up-front that kick out on failure are permissible, beauty-wise. Just no returns in the middle of the function's main processing.

      --
      Attention zealots and haters: 00100 00100
    50. Re:People hate my gotos by julesh · · Score: 1

      If goto were not useful or necessary then languages would have dropped it years ago when CS profs started to dread it because they couldn't teach their students properly and got tired of spitting out idiot programmer after idiot programmer who tortured them with goto-ridden spaghetti code.

      Which is presumably why languages like Pascal, Java, Python, Ruby, etc. all support goto.

      Oh, wait, they don't. Almost no programming languages designed since the 1970s do. C# is the only exception I can think of, and that was probably only implemented because the framework had to support it (in order to support BASIC) and C# is intended to support everything the framework can do.

    51. Re:People hate my gotos by Anonymous Coward · · Score: 0

      Oh O.K. So according to Slashdot, early returns and goto's are bad. So how do we handle the following? int func( int foo, char *bar ) { char *p; if( foo 42 ) return -EINVAL; if( !bar ) return -ESRCH; /* do stuff */ p = malloc( foo ); if( !p ) /* oh shit, now what? */ /* do more stuff */ return 0; }

    52. Re:People hate my gotos by Misagon · · Score: 1

      I often use goto's like that. People who are not do usually not understand that this is beautiful, structured code. I often use it when I have done a search through a complex data structure and do the goto when I have found what I'm looking for. Something I dislike in Java, is that you must have a statement after the label... instead of just a closing brace. Silly.

      --
      "We mustn't be caught by surprise by our own advancing technology" -- Aldous Huxley
    53. Re:People hate my gotos by Bill+Dog · · Score: 1

      You could do the malloc that you're assigning to p, up front where you declare p. Consider "enough memory available" one of the function's preconditions.

      On the other hand, in much of programming you just don't ever run out of memory (I never have in 11 years of PC programming), so it would be considered an exceptional case -- throw an exception.

      --
      Attention zealots and haters: 00100 00100
    54. Re:People hate my gotos by Misagon · · Score: 1

      Java does have goto, but reuses the keyword "break" and with some restrictions.

      --
      "We mustn't be caught by surprise by our own advancing technology" -- Aldous Huxley
    55. Re:People hate my gotos by Anonymous Coward · · Score: 0

      First your you are wrong about Pascal, it supports gotos but only to labels not line numbers. (A good choice in my view, though turbo pascal did support line numbers, I think) Java kind of supports gotos but only to break loops, it's really king of confusing for us old timers, because you place the label before the loop, I guess you label the loop. Or if you want go back to the begin of the loop you can use continue. As for Python and Ruby, you should see the shit people do instead of gotos, like wrapping their loops in functions and using return instead of goto, better yet lets use goto evil cousin try and catch (that makes for some pretty code) or yeah I see people do the same shit in Java and sometimes in C from people who don't know when to use gotos. These "solutions" get really ugly when you need to multi break outs in multilevel loops. People I have found the absence of gotos unbearable and have decided to add them; in the from of modules. Also gotos are great for optimizing code, yeah I rare nowadays but it happens. Of course I have seen my share of spaghetti loops and probably created one or two. I am also sure that if we look at runtime environments/compilers for Ruby and Python will see a few gotos which prove there usefulness.

    56. Re:People hate my gotos by Anonymous Coward · · Score: 0

      1) What if the malloc is based on an earlier calculation?
      2) How far into the function do you still consider it an "early" return?

      On the other hand, in much of programming you just don't ever run out of memory (I never have in 11 years of PC programming), so it would be considered an exceptional case

      3) I was going to say "I can't believe you just said that" but this is Slashdot, home of the mediocre, so actually I can believe you really did just say that. 11 years of programming you say? Please list companies & products so that we can avoid them.

      throw an exception.

      In C? Right. Let's give you the benefit of the doubt and assume it's C++: sure, an exception is obviously the correct thing to do. Now please tell me, how is an exception less complicated than an early return or even a goto in C?

      I swear to God, 99.999% of people who have posted on this thread need to either gain five more years experience or just go mow lawns. It's fucking criminal the level of understanding that is exhibited here. I may just submit the entire article to TDWTF.

    57. Re:People hate my gotos by morgan_greywolf · · Score: 1

      Hate to burst your bubble (because I basically agree with the spirit of your post), but Pascal supports gotos, at the very least all Borland Pascal compilers, Microsoft QuickPascal, FreePascal and gpc all support gotos.

      In Python (or Java), you'd do a try...for...break...finally instead of a goto, which is like a restricted goto, but, fortunately, can't be used for arbitrary gotos.

      And, yes, another programming language designed since the 1970s supports a GOTO, although it's not a traditional goto, it can cause the same sort of spaghetti code: Perl. :)

    58. Re:People hate my gotos by mrjimorg · · Score: 1

      Actually, this isn't always so nice:
      while(loop1)
      {
          while(loop2)
          {
              do_some_alloc();
              if(alloc_failed)// need to break completely out due to say.... malloc fails
                need_to_break_out = 1;
                break;
          }
          if(need_to_break_out)// UGLY!!!!!
              break;
      }

      As for "Just wrap them up inside a function and 'return' from it, instead of goto-ing to the end", this doesn't always work because in the example above returning would cause us to leak all the resources that we've alloced so far. We could free these resources, but that would require 2 more nested whiles (yuck!). Although, usually will have a dealloc function that will perform frees so you could call that before break, but you need to make sure you set things up to be able to call that function from an aborting alloc function (initialize all your pointers early).<br>
      After using do{}while(0) for years just to avoid gotos, I've accepted that perhaps they're not so bad after all.

    59. Re:People hate my gotos by Anonymous Coward · · Score: 0

      You don't know too many languages do you? And you are wrong about Pascal (check the "label" section). And if Java, et. al., are your examples of good languages, you are probably a crappy programmer anyways. Even, Ada, arguably the safest language, has a goto. The simple fact is that goto makes some types of software (i.e., auto-generated) easier to create, which is well (real) modern languages still support it.

    60. Re:People hate my gotos by Anonymous Coward · · Score: 0

      What's your point??? C goto goes to labels, not line number, too. As does Ada's.

    61. Re:People hate my gotos by Anonymous Coward · · Score: 0

      That's completely untrue. Just because you say "goto" instead of "break" does mean the compiler is unaware of scope! For example, in C++, it is illegal for a goto to skip over variable initialization. And a goto that jumps back before a variable init. causes the current incarnation of that variable to go out-of-scope and be destructed.

    62. Re:People hate my gotos by Anonymous Coward · · Score: 0

      Exception should be exceptional. DO NOT used them for path control!

    63. Re:People hate my gotos by DragonWriter · · Score: 1

      If goto were not useful or necessary then languages would have dropped it years ago


      Uh, no. Languages, particularly ones in wide use where continued support of legacy code is important, don't, in the real world, necessarily drop features just because they aren't useful or necessary if they are in wide use in existing code, even if that code is poorly written. So you can't infer utility from the fact that it still exists.

      Plenty of newer languages (and, for that matter, some older ones), of course, don't have gotos, and get along just fine without it. Gotos may or may not be useful in languages more abstract than assembly, but they certainly aren't necessary.
    64. Re:People hate my gotos by renoX · · Score: 2, Interesting

      [[ When I am reading code and I see a break statement, I know where the flow goes. When I see a goto statement, I have no idea where the flow goes ]]

      Sure because it's really difficult to see where 'goto end_loop_foo' goes..

      There are three common idioms where goto are useful: breaking nested loops, going to a return error section at the end of a function or to code a state machine, in the first two case that's perfectly valid to use goto and labelled break or exception doesn't bring much, but it's true that for the third using an array for the transition helps the readability (a little, big state machine are hard to understand however you code them).

    65. Re:People hate my gotos by Estanislao+Mart�nez · · Score: 1

      They /can/ be a signal for bad code, but they /can/ make certain types of code much clearer, e.g. iy you have a long list of test cases that you wish to test in turn - exiting any one if it fails.

      I guess I wasn't as clear as I could've. If you write a function that's a big if-then-else statement with many clauses, it's ok to have return statements as the consequents of the clauses, even if they're "in the middle" of the function. This code is readable because it's clear what the structure is: it's a sequence of parallel conditional clauses. You can see from a quick look that in any one invocation, only one of the conditions will ever be successful. Also, if all the consequents return from the function call, this is an example of parallel structure, which is something that tends to make both text and code more readable. (Comparing this to the way Lisp does this is instructive; in Lisp, you'd use a single multi-clause conditional expression like COND; from seeing COND in the code, you immediately know that the outer layer of the logic is a multi-clause conditional, and that only one of the clauses will succeed.)

      The key point I'm trying to make is more or less your point: the complaints about return "in the middle" of a function is really a complaint about code that doesn't make its flow control evident.

      Closely related to using return "in the middle" of a function, another code smell is using a lot of if-then statements where you could have used a single if-then-else statement. If-then-else is good, because it makes it visually clear from just looking at the code that only one consequent will be executed in any call, and therefore, means that to understand the function, you may not need to consider cases where more than one of the blocks of code is executed. To use a bad example, if you have a long if-then-else statement with 8 clauses, the syntax of the language guarantees that only one of the consequents is run each time, for a total of 8 possibilities; if you have the equivalent without the else clauses, there are, in principle, 256 different combinations of consequents that could get called, and the only way you can figure out that 248 of these can never happen is by reading the code carefully.

    66. Re:People hate my gotos by Bill+Dog · · Score: 1

      ...but this is Slashdot, home of the mediocre,...

      This is Slashdot indeed -- you think anyone who doesn't do imbedded programming is "mediocre". Grow up.
       
      ...how is an exception less complicated than an early return or even a goto in C?

      Because the caller doesn't necessarily need to handle the error -- it could be handled further up the call chain. It makes sense to have a function return indications of common, anticipated error conditions, such as a user having entered a bad file path. But integrating code into a function for uncommon, unanticipated error conditions unnecessarily dilutes and distracts.

      Using switch-cases for example isn't really any less complicated than goto's, and all conditional and iterative constructs in modern languages can be replaced with goto's, that wouldn't really complicate things, except to remove the extra expressiveness of choosing a particular of these constructs over the others. In the above situation, an exception is a clearer expression of that category of failure.

      --
      Attention zealots and haters: 00100 00100
    67. Re:People hate my gotos by DuckWizard · · Score: 1

      I think you missed my sarcasm. My point was that whatever language constructs you use to accomplish a certain execution flow will be largely irrelevant, as it will end up being pretty much the same once the compiler's done with it.

      Of course it would be madness to drop the JMP instruction, as it is necessary for pretty much any flow control whatsoever. Using goto is essentially placing a JMP in your high-level code. Hardly the capital sin that many coders make it out to be.

    68. Re:People hate my gotos by locster · · Score: 1

      I think we're pretty much in agreement then. Like I say, it's the coders that blindly follow rules without thinking about why that really gets me. Or even worse, the ones that think they're obviously better than you because they've spotted this glaring 'error' in your code :)

      It's classic Dunning-Kruger effect

    69. Re:People hate my gotos by Jaime2 · · Score: 1

      I'm not saying the compiler is necessarily unaware of it, I'm saying the compiler has to figure it out. With a break, it is explicit. By announcing your intentions to the compiler, it can tell you when you are doing something that is inconsistent with the design of the application. This comes in very handy when you modify the code in the future by making it harder to unintentionally introduce bugs.

      Also, modern compilers are good at this kind of stuff. I'll bet a lot of old (like 1960's old) compilers blindly turned GOTOs into JMPs.

    70. Re:People hate my gotos by Paradise+Pete · · Score: 1
      Dude, that should obviously be:

      loop_1:
      if(bail_on_1) goto loop_done;
      reset_bail_2;
      loop_2:
      if(bail_on_2) goto loop_1;
      do_work;
      if(bail_on_2) goto loop_extra_check_for_safety;
      goto loop_2;
      loop_extra_check_for_safety:
      if(bail_on_2) goto loop_1;
      goto loop_2;
      loop_done:
      ta_da;

    71. Re:People hate my gotos by bensch128 · · Score: 1

      Return statements in the middle of the a function body are usually a good signal of bad code; they make the flow of the code more obscure. However, they usually come hand in hand with a clearer signal: functions that are too long.

      You are kidding right? The point of putting the return in the middle of the function is to leave the function as soon as the processing is over. Not to have to set an error flag, break, check the error, break and check the error again. Returns allow proper deinitialization to occur where gotos simply jumps all over the frame and can cause variables to not be initialized or deinitialized properly.

      for example:
      goto foo;
      int bar = 42;
      foo:
      printf("bar = %d", bar);

      whats the value of bar?

      Ben

    72. Re:People hate my gotos by mrjb · · Score: 1

      "making it a nightmare to [...] mathematically prove [...]"

      Intriguingly, "mathematical proof" is always used as an argument against goto, but never against other flow control constructs such as while loops or break in a switch/case statements.

      Semantically,

      function a(b) {
            if (b==null) goto endfunc;
            do_something();
      endfunc:
      }

      and

      function a(b) {
            if (b!=null) {
                  do_something();
            }
      }

      are entirely equal. So why would one be harder to prove than the other?

      Over time we have seen new flow control statements being introduced. One of the more recent additions is try/catch/finally. It doesn't seem far-fetched to me that some acceptable uses of goto simply haven't been captured in flow control statements yet.

      Then for something besides the point- in the real world, I have yet to run into the first coder that uses the 'Mathematical proof' argument *and* actually mathematically proofs his code. Could it be that you are the exception to that rule?

      --
      Visit http://ringbreak.dnd.utwente.nl/~mrjb/growingbettersoftware to download your free copy of the book
    73. Re:People hate my gotos by Plutonite · · Score: 1

      Could it be that you are the exception to that rule? For most hacks, no. For work that goes into academic papers (I am a theorist, theory of computing..etc), yes. Also, whether or not it (proof) is put into practice is entirely irrelevant. As for your example, that was too simple. Try some spagetti code with induction and savor the aromas of confusion :)
  6. Sure... by skoaldipper · · Score: 1

    Programmer - You are sooo beautiful. My masterpiece. My pies de resistance!
    [ Kisses screen and compiles code into native instruction set ]
    CPU - Hmm. Where have I seen your fugly face before?

    --
    I hope, when they die, cartoon characters have to answer for their sins.
    1. Re:Sure... by WhiteWolf · · Score: 1

      Hello world, is that you?

      --
      Eye kneed eh Grammer chicken.
    2. Re:Sure... by Anonymous Coward · · Score: 0

      Somebody please mod this up! You fugly faced mods!!

    3. Re:Sure... by TheLink · · Score: 1

      Cache, Second Level.

      --
  7. Have to say... by Reality+Master+101 · · Score: 0

    I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments. My favorite whipping boy example of this is 'ssh', one of the more critical applications. If I had written that thing, I'd be hiding my head in shame (apparently Theo seems pretty proud of it, though).

    I'm sure there has to be *some* good examples of open source beautiful code out there (heck, I know at least one exists... I released it myself a long time ago. I'm a huge believer in well commented, well structured, understandable code), but I have yet to see a really good example other than my own.

    --
    Sometimes it's best to just let stupid people be stupid.
    1. Re:Have to say... by Anonymous+Crowhead · · Score: 5, Funny

      I have yet to see a really good example other than my own.

      I, too, am the only one I know who writes decent code.

    2. Re:Have to say... by kevin_conaway · · Score: 4, Interesting

      I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments

      I struggle with this. When I was in school, my instructors drilled into me the importance of documentation and comments. Now that I've been in the real world, I have to say that I don't agree.

      The problem with comments is that you now have two things to maintain, the code and the comments. Often time this is OK for a single developer but for someone coming in to maintain a piece of code, often times they are hesitant to touch the comments especially if they are wrong.

      I find that (for me at least) I have the greatest success with short, composed methods that do one thing and one thing well all backed up by unit tests that test behavior and requirements, not simply that foo() returns 15.

      You might be thinking that I'm contradicting myself here because now I have to maintain both code and tests. However, I feel that the tests provide much more value in that once a test for a piece of code works, you now have confidence in that piece of code. If you miss something with the test, its a simple matter of adding a new test for that case.

    3. Re:Have to say... by Reality+Master+101 · · Score: 4, Insightful

      Now that I've been in the real world, I have to say that I don't agree.

      I have to respectfully say that if you believe this, you haven't written 1) enough code, and 2) complex enough code, to have filled up your brain sufficiently to where you can't remember what the hell you were thinking at that time. When you've reached that level of programmer maturity, THEN you will understand the importance of comments. :)

      Never mind trying to blaze the trail for programmers that come after you. I also predict that you haven't tried to unravel another programmer's crappy code.

      The problem with comments is that you now have two things to maintain, the code and the comments

      Yes. People who change code but don't update the comments should be flayed appropriately.

      I find that (for me at least) I have the greatest success with short, composed methods that do one thing and one thing well all backed up by unit tests that test behavior and requirements, not simply that foo() returns 15.

      Testing and commenting are two different subjects. Comments are not to tell you that "foo() returns 15", comments are to tell you the *context* of code, how it fits in with the overall goal of the subroutine.

      --
      Sometimes it's best to just let stupid people be stupid.
    4. Re:Have to say... by GrievousMistake · · Score: 1

      I don't know why you'd single out open source, this applies to code at large. I think it's just one of those '90% percent of everything is crap' things.

      --
      In a fair world, refrigerators would make electricity.
    5. Re:Have to say... by yuda · · Score: 1

      I've been webcoding sice around '01. I've recently had to go back and do some work on a site I haven't touched in around five years. The thing I found was really ugly code and almost no comments - ok I was using dreamweaver at the time and have graduated to hand coding since. It was bloody hard to do even quite basic alterations. I was half tempted to do a complete re-design using css and w3c standards. As it stands at the moment I'm pretty embarrased that I ever set such ugly code into the wild

    6. Re:Have to say... by gmf · · Score: 1

      I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments. The sad thing is, as far as I can tell, this is true for the vast majority of closed source code as well. You just don't tend to see closed source code as often...
    7. Re:Have to say... by Reality+Master+101 · · Score: 1

      I don't know why you'd single out open source, this applies to code at large. I think it's just one of those '90% percent of everything is crap' things.

      I agree that a lot of closed source code is crappy as well, but there's at least a chance of institutional standards that can be enforced. There's also a higher proportion of professionals that believe in good code, whereas you have a higher proportion of amateurs for OSS (because anyone can work on an OSS, but not everyone can manage to be hired at a company).

      --
      Sometimes it's best to just let stupid people be stupid.
    8. Re:Have to say... by HoosierPeschke · · Score: 1

      Don't feel bad, I've used FrontPage and designed IE only sites before... now it's all proper xhtml and css. The best thing about making mistakes is learning from them.

      --
      Mr. Universe: "They can't stop the signal, Mal. They can never stop the signal."
    9. Re:Have to say... by kevin_conaway · · Score: 2, Interesting

      I have to respectfully say that if you believe this, you haven't written 1) enough code, and 2) complex enough code, to have filled up your brain sufficiently to where you can't remember what the hell you were thinking at that time. When you've reached that level of programmer maturity, THEN you will understand the importance of comments. :)

      Again, I think that this is where the importance of short, composed methods really shines through. If every method you're looking at is 5 - 10 lines long, its a lot easier to grasp what a block of code is doing. Of course, one could get carried away and get "delegation happy" but thats what a good debugger is for :)

      Never mind trying to blaze the trail for programmers that come after you. I also predict that you haven't tried to unravel another programmer's crappy code.

      I have and its unpleasant. At my previous job, I worked with some poor developers who happened to be non-native English speakers. When comments are written in English and the person writing them does not have a solid command of the language, it can get ugly.

      I'm young in my career and time could certainly change my attitude but for the time being, I stand by my original post.

    10. Re:Have to say... by Porchroof · · Score: 1

      So, you would rather write code and tests rather than code and comments?

      Sounds to me like more work and less information available for the poor fool who has to maintain that code after you leave.

      And WTF do tests have to do with writing and maintaining code? You have to test everything regardless of how pretty or informative your code is.

      All of the programmers (I wouldn't call any of them "software engineers") whom I've worked with the past 25 years thought that writing comments to their code was for wimps. (Much like the pickup truck drivers who think their balls will shrink if they turn on the headlights on a rainy day.)

      Frankly, they just don't want to be bothered writing maintainbale code because it takes time and requires some intelligence. (I'm talking about you, Bob, Ron, John, Dan or whoever's left at FAPD.)

      --
      Fata viam invenient.
    11. Re:Have to say... by mrchaotica · · Score: 1

      If every method you're looking at is 5 - 10 lines long, its a lot easier to grasp what a block of code is doing.

      Sure, you can figure out what the code is doing, but in order to know why the code is doing it you still need comments.

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    12. Re:Have to say... by Breakfast+Pants · · Score: 1

      It is much easier to get hired at a company than to produce open source code that anyone other than you will ever either use or look at.

      --

      --

      WHO ATE MY BREAKFAST PANTS?
    13. Re:Have to say... by quanticle · · Score: 1

      Tests can be a form of documentation too. A proper suite of unit tests will show exactly what a method does. If the method does something different than expected then the tests will fail.

      --
      We all know what to do, but we don't know how to get re-elected once we have done it
    14. Re:Have to say... by n+dot+l · · Score: 1

      I, too, am the only one I know who writes decent code. I used to think that way. And then this one time I ran across some really beautiful code out on the net that I (eventually) had to admit I hadn't written.

      Coming to that realization was the hardest thing I've ever had to do.

      </kidding>
    15. Re:Have to say... by Ungrounded+Lightning · · Score: 1

      The problem with comments is that you now have two things to maintain, the code and the comments.

      The problem with NO comments is that debugging can not determine wither code is correct - it can only find whether two representations of a solution are equivalent. "The code is the documentation" means the only thing that can be tested is the compiler.

      This is because what is correct varies, depending on what the job is. (You may have written a bug free version of "cat". But it's very badly broken if you intended to write "ls".)

      So a good programmer writes TWO versions of his program - in representations as different as possible. (Preferably one optimized for automated translation, one for human readability.) That way he's thinking in different mindsets, greatly reducing the likelihood of making identical errors in both representations.)

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    16. Re:Have to say... by Reality+Master+101 · · Score: 1

      Tests can be a form of documentation too. A proper suite of unit tests will show exactly what a method does.

      This is silly. 1) Instead of reading reasonable comments, I'm supposed to dig out the module test and read the source code to see what that does, to tell me what a module does? 2) A test suite tells me nothing about how a method is used in the overall context of the program -- the whole point of comments. 3) Method comments are only one type of comment. I full expect methods within the code telling me exactly how it's doing what it's supposed to do.

      --
      Sometimes it's best to just let stupid people be stupid.
    17. Re:Have to say... by smellotron · · Score: 1

      So, you would rather write code and tests rather than code and comments? Sounds to me like more work and less information available for the poor fool who has to maintain that code after you leave.
      Tests are typically better documentation than inline comments, because
      1. it's easy to verify that they are correct (if the test suite runs, they are correct)
      2. they provide a wealth of examples of how to use a piece of code, likely moreso than any comment will
      The things that you can't capture in code or tests is semantics. Who cares what the syntax of a function is, if I don't understand its purpose? Someone's inline comments aren't going to do that. It's going to be a combination of
      1. intention-revealing function/class/variable names (what tells me more about an accounting system? plus5(x) or plusServiceFee(cost)?)
      2. architectural documentation. Not API-level documentation. Design documentation discussing what the entire piece of software is the way it is (is it set up as a chain of pipes and filters? why? What information goes through the pipes, and what do the filters do?).
    18. Re:Have to say... by Nevyn · · Score: 3, Insightful

      The problem with NO comments is that debugging can not determine wither code is correct - it can only find whether two representations of a solution are equivalent.
      ...
      So a good programmer writes TWO versions of his program - in representations as different as possible. (Preferably one optimized for automated translation, one for human readability.) That way he's thinking in different mindsets, greatly reducing the likelihood of making identical errors in both representations

      Who cares about identical errors, you're screwed either way then. The big problem is when the "documentation" and the "code" don't match ... you have no idea which one is wrong.

      As the old saying goes: "The man who has a watch knows what time it is, the man who has two is never sure." ... of course the man who has one watch and a big pile of unit tests which prove it's keeping the right time is doing the best of all :).

      I've been at this for a pretty long time now, and I've found very little use for "comments explaining what the code does" ... but a lot of use for "comments explaining why". And personally, I've gone back to code I've written over 5 years ago and could see what it was doing instantly ... and on the bad side I've read code I wrote a year or so ago and not understood why it was doing something (to be fair, after thinking about it a bit it became "obvious" ... but then I wrote a comment explaining it anyway :).

      Yes, I've read others peoples code that (in theory) would have been easier to understand if it had been heavily commented ... but it would have been even easier to read if they'd just been any good at what they were doing and written the code well.

      --
      ustr: Managed string API with ave. 44% overhead over strdup(), for 0-20B
    19. Re:Have to say... by syousef · · Score: 1

      The real problem with comments (and tests unless you run continuous integration) is that they break easily ie. you can easily change the code without changing the comments.

      You really need all 3 to have a decent system maintainable by a group:
      1) Good neat code with well named identifiers
      2) Comments
      3) Tests

      Yes that's 3 times the work and 3 times the maintenance. You get nothing for nothing.

      So how can you minimize the work?

      Good choice of granularity when commenting and testing.

      For commenting always comment what isn't obvious from the well written code. You don't need a comment telling you that the method String getPersonsName() returns a string. The return type is staring you in the face. If the return type changes it's easy to accidentally miss the comment when modifying the code, particularly if you're making big changes. The method calculateTaxRate(...) shouldn't have a comment stating that you calculate the tax rate. It should explain the method used and refer to an external document if that explanation is too long. Asinine development standards would insist that we comment these. That's BS.

      For tests, lets say you have a business layer and a data layer, and the business layer trivially calls the data layer. Do you really need a test at every layer? Perhaps a data layer test is enough if you're certain the business layer isn't likely to break. If it is, perhaps the business layer can do both. Half the code you have to write and maintain, but twice as much relying on that one test, so get it right.

      --
      These posts express my own personal views, not those of my employer
    20. Re:Have to say... by MrMr · · Score: 1

      I'm not surprised at all, some bits of my code are out there.

    21. Re:Have to say... by milwcoder · · Score: 1

      If you have short and myriad number of methods with no comments, it'll be fine as long as your company keeps you around, hire the elite 10% of developers that can read them or have programmers that only have the capacity to work with a small portion of the code base at a time. With many undocumented short methods, the way to understand code, is to procedurally spaghetti through lots and lots of methods and class files just to see how one thing gets done. Very often, adding some complexity in the local level can simplify the overall complexity at the global level (number of methods, inheritance levels and class files). If this approach combines with non-descriptive method names, reading code will be like reading the alphabet soup. Some code needs to be together and duplicated *gasp* when it makes sense, it is better for performance when it is fine tune-able for each implementation and not cause grief when people have to code around the shared utilities.

    22. Re:Have to say... by Crimsonjade · · Score: 1

      The problem with comments is that you now have two things to maintain, the code and the comments. When I see someone say this, changes are they do not commenting very well to begin with. My comments usually reflect the overall process of the program, not what the code is doing. As such, a section of code that I wrote can be changed and the comments are still applicable.
    23. Re:Have to say... by Anonymous+Brave+Guy · · Score: 1

      I think you're talking about what is commonly described as "self-documenting" or "self-commenting" code. You're absolutely right that well-designed and well-written code reduces the need for comments dramatically. If each element of your program has a single, clear responsibility, and the names and interfaces reflect those responsibilities, then yes, it's quite possible that you can write many functions with few or any comments needed.

      However, the more experienced programmers who are disagreeing with you to an extent also have a point. While the "self-documenting" approach removes the need for comments that describe what is being done — the code itself documents that — someone coming along later to fix a bug, or finding their way around an unfamiliar large system, will rarely be able to determine why something is done as it is just from reading the implementation. This is the time when one good comment is worth a dozen class diagrams and flow charts.

      You don't mention how experienced you are, so perhaps you've been here already, but if you've yet to read some of the classic general programming books like Code Complete, I highly recommend them. You'll find a lot of thought-provoking ideas in there if you're an interested but so far relatively inexperienced programmer.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    24. Re:Have to say... by Anonymous+Brave+Guy · · Score: 1

      Fortunately, the programming community is just one big, happy family. In fact, in a recent survey, 99% of programmers agreed that 99% of programmers can't program for ****.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    25. Re:Have to say... by Anonymous Coward · · Score: 0

      Mr. Universe: "They can't stop the signal, Mal. They can never stop the signal."

      Then why didn't Mal just upload the hologram to Mr. Universe in the first place??

    26. Re:Have to say... by obarel · · Score: 1

      I totally agree - the one example I always give when I meet a "self-documenting code" programmer is the case of implementing a standard.

      You accept one form of floating point, but reject another - the code is crystal clear, but the customer wants to be able to write 3.8e+8 and you don't allow it. Another programmer goes into the code and quickly changes it to allow that 3.8e+8 format. Next thing a test fails (the test that makes sure that 3.8e+8 will not be accepted). The programmer thinks "ah, that's a bad test, it doesn't allow all possible floating points formats, probably someone was day-dreaming" and quickly changes the test not to fail.

      So far, so good - the code was clear, the test was clear, but someone, somewhere will have a very big problem with the "numbers separated by the character 'e'" case as described in the standard.

      A comment /* Not allowing other formats, as per section 3.27.1.55.3 of the standard */ is all it takes.

    27. Re:Have to say... by DragonWriter · · Score: 1

      . However, I feel that the tests provide much more value in that once a test for a piece of code works, you now have confidence in that piece of code. If you miss something with the test, its a simple matter of adding a new test for that case.


      A test doesn't replace documentation. Documentation describes what the code does. A test verifies that, in the case covered by the test, the code does, in fact, do what it is intended to do. But you can't infer the information in good documentation from an (undocumented) test suite, because while the test cases will specify behavior in specific conditions, you can't (generally) unambiguously infer what behavior is expected in other conditions, particularly when the task being tested is nontrivial. A test is always a specific case of an operationalization of a specification, even if no one has ever reduce the specification to writing. But it would be good if they did. Its true that good documentation isn't always worth the effort, but its equally true, I think, that it is almost always more worth the effort than it would seem intuitively at the time the code is written, so if the impression at the time of first developing the code is the guide to documentation, code always ends up underdocumented which tends to cause problems down the road.
    28. Re:Have to say... by quanticle · · Score: 1
      From Pragmatic Unit Testing:

      Once nice side-effect of unit testing is that it helps you communicate the code's intended use. In effect, a unit test behaves as executable documentation, showing how you expect the code to behave under the various conditions you've considered. Team members can look at the test for examples of how to use your code.
      As for "digging out the the module test", there's no digging if you have your tests placed in the same module as your code, and use configuration management to strip out the tests when you release code.
      --
      We all know what to do, but we don't know how to get re-elected once we have done it
  8. The problem with the book... by BlueBoxSW.com · · Score: 5, Funny

    Anyone else have laugh when they looked at the cover of the book?

    A Flock of Birds?

    To symbolize beautiful code?

    Flock-of-Birds-style code is the UGLIEST code out there!

    Used only by those who haven't learned to use case statements, build databases, or define arrays.

    Is this beautiful code???

    if(something==interesting)
        if(somethingelse==goodcode)
            if(somethingother==blahblahblah)
                if(somestupidbookcover=birds)
                    doSomethingUseful();
                else
            else
        else
    else
        if(somethingelse==goodcode)
            if(somethingother==blahblahblah)
                if(somestupidbookcover=birds)
                    doSomethingUseful();
                else
            else
        else
    end if

    1. Re:The problem with the book... by morgan_greywolf · · Score: 2, Funny

      There's a name for that garbage? Well, color me stupid. Learn something new every day.

    2. Re:The problem with the book... by intx13 · · Score: 1

      I dunno.. it could have been a big plate of spaghetti, or as my boss likes to say "a tornado hitting a spaghetti factory".

    3. Re:The problem with the book... by Anonymous Coward · · Score: 0

      Is this code at all? What language allows you to end an if block with an else?

    4. Re:The problem with the book... by Sax+Maniac · · Score: 1
      --
      I can explanate how to administrate your network. You must configurate and segmentate it, so it can computate.
    5. Re:The problem with the book... by barkingcorndog · · Score: 1

      Anyone else have laugh when they looked at the cover of the book?

      A Flock of Birds?

      To symbolize beautiful code?

      Flock-of-Birds-style code is the UGLIEST code out there!

      Used only by those who haven't learned to use case statements, build databases, or define arrays.

      Is this beautiful code???

      if(something==interesting)
      if(somethingelse==goodcode)
      if(somethingother==blahblahblah)
      if(somestupidbookcover=birds)
      doSomethingUseful();
      else
      else
      else
      else
      if(somethingelse==goodcode)
      if(somethingother==blahblahblah)
      if(somestupidbookcover=birds)
      doSomethingUseful();
      else
      else
      else
      end if
      I wouldn't consider that to be beautiful code, since your first conditional if(something==interesting) is completely unnecessary. The else branch does exactly the same thing.
      --
      "I know together we'll make the possible totally impossible" - Homme
  9. beautiful code by lottameez · · Score: 4, Funny

    while (1){
    Beer b = (Beer)getBeer();
    drinkBeer(b);
    belch(BelchType.LOUDLY);
    }

    --
    Yeah? Well I think you're overrated too.
    1. Re:beautiful code by RetroGeek · · Score: 2, Funny
      You forgot to add inside the loop:

      Bladder blad = Bladder.getInstance();
      if ( blad.isHurting() )
      {
        bld.empty();
      }
      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    2. Re:beautiful code by RetroGeek · · Score: 1

      Sigh...

      that would be:
      blad.empty();

      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    3. Re:Beautiful Code by Fahrenheit+450 · · Score: 1

      Where are the Test-Case Discussions. Beautiful code needs testcases that are the same.

      Perhaps in chapters 6 and 7?

      --
      -30-
    4. Re:beautiful code by garett_spencley · · Score: 1

      It's times like this I wish you could moderate +1 Sexy

    5. Re:beautiful code by Anonymous Coward · · Score: 2, Funny

      Let us pray getBeer() does not return a Singleton.

    6. Re:beautiful code by Mind+Socket · · Score: 1

      I hope you've got a good garbage collector to deal with all those empty beers.

    7. Re:beautiful code by julesh · · Score: 1
      I've fixed it for you

      while (! wallet.isEmpty()){
        Beer b = bar.buyBeer(wallet);
        drinkBeer(b);
        belch(BelchType.LOUDLY);
      }
      try {
        scroungeDrinksFromFriends();
      }
      catch (DrunkTooMuchException e) {
        throw up;
      }
    8. Re:Beautiful code by julesh · · Score: 1

      IE if it takes you 2 years to write beautiful correct code that is maintainable and works perfectly AND your project is two years late to market **you still suck**

      If it takes 2 years to write the code and you're 2 years late to market, you really need to find another market.

  10. Most code is beautiful at one point in time by intx13 · · Score: 4, Insightful

    Most code is beautiful at one point in time - namely, when it's first written. A decent programmer can produce some decent code that performs the task at hand elegantly. With a little work this can become beautiful. Most applications I write start out very elegant, beautiful, commented, clever, etc. - It's only after the project grows and I'm working on a file named "main4.3.a.iii.bak2.worksithink.c" that the comments turn into "// why is this here?" and the variables go from "nDBEntryCount" to "temp" and the code becomes an ugly mess.

    The real trick is DESIGNING the application in such a way that it can grow gracefully, and STAY beautiful. And that's really tough - knowing what sorts of features and requirements the future will hold is difficult. A big part of this is the language itself - I love assembly languages, and I could write some really clever and beautiful assembly code. But when the requirements change and the code needs a new feature? There goes all the carefully timed loops and cycle counts!

    Beautiful code is as much beautiful, expandable, future-proof design as it is beautiful implementation.

    1. Re:Most code is beautiful at one point in time by DittoBox · · Score: 1

      Code is pretty. Programs are beautiful.

      --
      Good. Cheap. Fast. Pick Two.
    2. Re:Most code is beautiful at one point in time by garett_spencley · · Score: 1

      The real trick is DESIGNING the application in such a way that it can grow gracefully, and STAY beautiful. And that's really tough - knowing what sorts of features and requirements the future will hold is difficult.

      You've just described why reusable code, and simplicity, is so important.

      You started off hitting the nail on the head. Applications need to be designed so that they can grow with grace and retain their elegance. However, it is impossible to predict the future and I've seen so many projects where the list of "to be supported in the future" lead to so much foundation code that's only purpose was to support features that never came to pass and they became bloated. Sure they had the room to support those features, but as the requirements grew further and further away from what the designers originally thought was going to happen, the application just ended up becoming a mess.

      Thus what you need to do is design everything to be re-usable and extensible. Write your functions, classes, interfaces, libraries etc. to do one thing only, and do it very well. When you start to see a block of code getting too big, break it down into smaller blocks. Design for the possibility of unlimited extension in the future without knowing what the future will demand of your project. And most importantly, keep things as simple as possible, and continue to do so as you add more features.

    3. Re:Most code is beautiful at one point in time by gmf · · Score: 1

      Yeah, you should design your code from the start in a way that allows it to grow and stay beautiful. But don't forget about refactoring. When it turns out that things don't fulfill the needs the way they are, don't just work around it by adding even more messy code. Of course, changing the structure of your code to adjust to new requirements takes time, but sometimes it's the only way keep things clean. And sooner or later you'll be glad you did it.

    4. Re:Most code is beautiful at one point in time by Anonymous Coward · · Score: 0

      You mention "clever" code. But there's a problem with clever code. "Clever" is usually a synonym for "doing something in a really weird way, that could easily be done in a simple, much more elegant way, just because the original coder thought it was neat". Like using a for() loop, and modifying the test inside the loop. Clever is generally the enemy of elegant.

    5. Re:Most code is beautiful at one point in time by julesh · · Score: 1

      the comments turn into "// why is this here?"

      One easy way to tell: remove the code, and see what breaks.

      Only works if you have automated tests for every feature you've implemented and every bug you've fixed, but is there a good justification for not having such tests?

    6. Re:Most code is beautiful at one point in time by julesh · · Score: 1

      it is impossible to predict the future and I've seen so many projects where the list of "to be supported in the future" lead to so much foundation code that's only purpose was to support features that never came to pass and they became bloated. Sure they had the room to support those features, but as the requirements grew further and further away from what the designers originally thought was going to happen, the application just ended up becoming a mess.

      Extreme Programming has a maxim, "You Ain't Gonna Need It", which applies to this sort of situation. The idea is, you work on the program one feature at a time, and don't implement anything that you don't need for the feature you're currently working on. Because requirements change, there's a better than average chance that the framework code you're thinking about writing isn't necessary, or isn't quite right, or is complete overspecified. Implementing it later (when the requirements are better known) will be easier and less likely to cause waste.

    7. Re:Most code is beautiful at one point in time by Bill+Dog · · Score: 1

      It depends on the requirements. This part of XP is just happy talk. Some things can be easily added later, but some cannot due to the approach chosen based on the requirements at the time. "Design for nothing extra" is indeed extreme. If you don't keep highly likely future requirements in mind when doing your initial design, you may very well find yourself in a "can't get there from here" situation, and having to throw out quite a bit of code.

      --
      Attention zealots and haters: 00100 00100
    8. Re:Most code is beautiful at one point in time by Anonymous Coward · · Score: 0

      That works on the gross physical level, but suppose removing the 'why is this here?' code works to modify a high level object in such a way that doesn't break anything.

      You might think you'd never do that, but business rules and policy enforcement find their way into code all the time.

      Those kinds of errors are hard to find before they go live. Nothing breaks at first, but maybe a resource allocation is incorrectly denied (or allowed and isn't available for someone who should have got it), or a week later an order is shipped to the wrong address, or any of a million other business errors. You won't catch that in unit testing (at least not if you have 'why is this here' code in production).

    9. Re:Most code is beautiful at one point in time by Communomancer · · Score: 1

      I remember reading a Pragmatic Programmers article from a few years ago...they argued that while you should adhere to the XP principle of YAGNI (You Aren't Gonna Need It) as much as possible, you still always had to be wary of the principle of DOGBITE (Do it, Or Get Bitten In The End). The trick is knowing which one best applies to any given situation. I guess that's what we get paid the big bucks for.

      The point is that, as in many things, balance is key.

      --
      "UNIX" is never having to say you're sorry.
    10. Re:Most code is beautiful at one point in time by Bill+Dog · · Score: 1

      But DOGBITE is not part of the XP dogma, YAGNI and DTSTTCPW (Do The Simplest Thing That Could Possibly Work) are. And people take it too literally, like maybe poster "julesh" above. XP is an over-reaction to the traditional process of developing software, and just flops us from one terribly unwise extreme to the other. It's best not taken as something to be exactly followed, but merely serving as an interesting jolt and challenge to the old ways of doing things, waking us up so that we think about how we've been doing things, versus just doing it that way because we always have.

      --
      Attention zealots and haters: 00100 00100
    11. Re:Most code is beautiful at one point in time by julesh · · Score: 1

      That works on the gross physical level, but suppose removing the 'why is this here?' code works to modify a high level object in such a way that doesn't break anything.

      In that case, you don't have adequate unit tests. The key to writing unit tests properly is to make sure that for each code execution path in the application there is at least one test that will fail if you remove that path (or, conversely, using the approach of test driven development: don't implement a code path until there's a test that will show whether or not it worked). If you have followed this rule, then there will not be any code in your system that wouldn't break anything if it wasn't there.

    12. Re:Most code is beautiful at one point in time by Anonymous Coward · · Score: 0

      In that case, you don't have adequate unit tests. To adequately test business rules expressed in code is entirely possible - but the programmer has to either be a domain expert and psychic to boot or have a very good customer representative who not only actually understands and can communicate their requirements but is capable of verifying that the unit tests truly test those requirements.

      Business rules code with a 'why is this here?' comment pretty much guarantee that this is not the case. They indicate a feature that was a rush job for some reason, and the #1 rule of rush jobs is that the only requirement you get is "make this work. Right Now".

      I think unit testing is one of the best construction quality steps you can take with your code. But I know that the boundary between integration testing and unit testing is a serious weakness. When the programmer happens to be a domain expert then things work out pretty well, otherwise testing business logic tends to be a grey area - and often gets forgotten entirely when things are rushed.
    13. Re:Most code is beautiful at one point in time by julesh · · Score: 1

      To adequately test business rules expressed in code is entirely possible - but the programmer has to either be a domain expert and psychic to boot or have a very good customer representative who not only actually understands and can communicate their requirements but is capable of verifying that the unit tests truly test those requirements.

      Business rules code with a 'why is this here?' comment pretty much guarantee that this is not the case. They indicate a feature that was a rush job for some reason, and the #1 rule of rush jobs is that the only requirement you get is "make this work. Right Now".


      Ah, I see your point now. The comment is to explain that the _requirements_ are unclear, not that the code is. That makes some sense.

      Still, such a comment wouldn't be in my code. The comment would say something more like "// this is necessary to make TestStupidObject.testThatInexplicableRule34aIsFoll owed pass", which is much clearer: the reason for the _code_ is fully documented. The reason for the test is perhaps unknown, but that's perhaps a little easier for somebody to figure out later.

      For the original commenter who mentioned these comments, I don't think this was the case. I'm pretty sure he was talking about code that had been mysteriously added to fix something broken, where he understood what was broken at the time, but just lost track of what the fix was supposed to do later on.

      My point is that if there is code to do something, there should be a unit test for it. If you understand the problem enough to write the code, surely you understand it enough to write a test that the code works correctly. I'll grant that you might not understand why the test is necessary, but that's an entirely different matter.

  11. Beautiful Code by Anonymous Coward · · Score: 0, Interesting

    It's nice that the code is beautiful, but is it FUNCTIONAL?

    Too many code monkeys spend hours hand-tweaking stuff, formatting stuff, forgetting it's about the FUNCTIONALITY.

    Where are the Test-Case Discussions. Beautiful code needs testcases that are the same.

    Another Book Written by and For Code Monkeys. Let know when the Engineering version comes out.

  12. Beware the raptors ... by Anonymous Coward · · Score: 5, Funny

    http://xkcd.com/292/

    That is all.

  13. Cool. You just wrote a bug. by Anonymous Coward · · Score: 0
    Look at the original (pseudo) code.

    When the condition that makes me want to bail occurs in the inner loop, the outer loop code is NOT executed again.

    However, your "fix" resulted in the outer loop code getting executed once after condition that makes me want to bail is reached in the inner loop.

    Lets hope you don't write avionics or life support software.

    Unfortunately, to maintain the original meaning and avoid the goto it takes:

    i=0; // I wonder why we are initializing counters for while loops
    while (not condition that makes me want to bail) {
                    j=0; // I wonder (again)why we are initializing counters for while loops
                    while (not condition that makes want to bail) {
                                      inner loop
                    }
                    if (not condition that makes me want to bail) {
                                      outer loop
                                      i++
                    }
    }
    Yes, that's right, you have to check condition that makes me want to bail 3 times

    hmmmm... Maybe goto's shouldn't be considered so harmful. Labeled breaks are probably the best thing. Simplifies the code but doesn't let arbitrarily you jump INTO a block.

  14. I've become jaded by syousef · · Score: 5, Insightful

    Is anyone else jaded by these books that go on and on about why a particular techique or code snippet or methodology is "right" or "beautiful" or "the way forward"?

    I look at some of the code mentioned and yes it's neat. Some of the code snippets from these books (not just this one specifically) is either really obvious or makes me want to blow chunks because it's an over-complication or over-simplification just to demonstrate a technique which you know will be over-applied and end up in some set of corporate standards that sees it being misused. ...then there's some of the frameworks and methodologies out there that are generally worshiped as God's own code, but which when you try to use them turn out to be cumbersome, horrible, unintuitive messes. Years later this is suddenly "discovered" (EJBs I'm thinking of you!!!) and a whole new set of horrible frameworks goes through several iterations (Hibernate 1 vs 2 vs Spring persistence, Struts vs Spring MVC) where nothing is allowed to mature for long enough to have the major bugs ironed out.

    Perhaps I'm just getting old but I'm really getting tired of all this. You want to know what makes code beautiful?

    1) It does the job 100% correctly as intended.
    2) It does it as simply as possible - not so simple it doesn't work, and no more complex than it absolutely needs to be...building everything in but the kitchen sink just in case is a fool's game.
    3) It's readable and well documented enough that anyone who knows the language (or better yet a programmer familiar with a similar framework but not this one) understands it.
    4) Its easy and quick to make changes as requirements change - that means GUI tools for GUI development (What ever happened to RAD tools being the norm in the industry!? It can take a week to make significant changes to a web page in Struts or Spring MVC, where it use to take about a day to do it for the clients developed with the RAD tools of the late 90s!)
    5) It fits in well with the rest of the system. A module that works beautifully in isolation but doesn't fit in with the system can ruin the system.

    All the rest is just a bunch of consultants trying to bilk you for cash.

    Yes patterns can help, but they can also hurt.
    Yes externalizing code into config files can make a system more flexible (but you'll pay for it in readability and tracability/debugability).
    Yes aspects of the agile methodology - continual integration and test driven coding - can help but they're not the only way and there's a cost associated.
    Yes Object oriented code offers things that procedural does not, but again there's a cost and your developers better understand the language constructs.

    You need to look at each of the above as tools in your arsenal, not religious doctrine.

    Note that my recent experience is with Java/J2EE so that's where my examples come from but I've worked on dozens of languages and frameworks.

    --
    These posts express my own personal views, not those of my employer
    1. Re:I've become jaded by RetroGeek · · Score: 2, Insightful

      You forgot "working within the langauge".

      I have seen examples where a person knows langiage A but is working with language B. And by God he WILL try to make language B work like language A, come hell or high water.

      This is where you get "clever code". Which is un-maintainable.

      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    2. Re:I've become jaded by syousef · · Score: 1

      Yeah I've seen that too - I use to know a guy in Uni who originally learnt BASIC, and always had a set of #defines in a header file he'd use to make BASIC constructs work in C. What a mess!

      --
      These posts express my own personal views, not those of my employer
    3. Re:I've become jaded by mrchaotica · · Score: 1

      Yes Object oriented code offers things that procedural does not, but again there's a cost and your developers better understand the language constructs.

      Or, how about this: OO code is beneficial when you're trying to solve an inherently OO problem, but not all problems are OO. Some are procedural, some are functional, etc., and you're better off using the appropriate paradigm for the task.

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    4. Re:I've become jaded by TrappedByMyself · · Score: 1

      Nice rant, but it really doesn't apply to this book.
      In fact the first chapter includes code which pretty much meets your criteria... The chapter is written by Brian Kernighan and it's about a small piece of code written by Rob Pike.

      Next time your complaint about broad generalizations which don't apply to their intended targets shouldn't itself be a broad generalization which doesn't apply to its intended target ;)

      --

      Help me take back Slashdot. When did 'News for Nerds' become 'FUD and Conspiracy Theories for Extremist Nutjobs'?
    5. Re:I've become jaded by n+dot+l · · Score: 1
      That reminds me of a random friend from high school that got pissed at me because I wouldn't help him fix a bug. In his defense, I did owe him money (and he was willing to take help in exchange for the debt) but after seeing this at the top of his "common.h" file I figured I'd just give him the cash and save myself some pain.

      #define begin {
      #define end }
      #define and &
      #define or |
      #define not !
      //etc
      In retrospect I should probably have just stripped out the system includes and run his code through a preprocessor before trying to read it, but that didn't occur to me at the time (probably because I was too busy being horrified).
    6. Re:I've become jaded by smellotron · · Score: 1
      The saddest thing is this

      #define or |
      #define and &
      instead of this

      #define or ||
      #define and &&
      If it confuses you to see "and", "or", and "not", that should make you sad (like the "I don't understand relationships between code and language" sort of sad). Though, I fully agree with you on the blocks (begin/end isn't any more logical than {/}).
    7. Re:I've become jaded by syousef · · Score: 2, Interesting

      Did you not even read what I said? You know the part about not referring to just this book. Mind you the blog site for the book that started going into detail about why Singleton (the most obvious fucking "pattern") is so "beautiful". I could have blown chunks right there. Effective and elegant if used correctly? Yes. A neat technique? Yes. Beautiful? Shit it ain't a non-obvious piece of elegance we're talking about here. ...and I couldn't care less who wrote it. Hero worship should have no place in computer science and engineering.

      By the way K & R - the supposed C bible - is one of the least readable C books I own! If you think I'm talking out of my backside I'll just tell you I had to use it to teach a C course once (long ago, an elective as and as a part time activity). Fortunately the previous lecturer's notes were stellar, and I had learnt from a different C book which I could refer to. This book confused more students than it helped (though the ones that like esoteric unintuitive dense but fully descriptive text did get something out of it). 90% of the students though many people that read K & R with no previous banground in C had no freaking idea how dereferencing worked. I spent an entire lesson on it because I think it's one of the key things that a good C programmer understands the MEANING of, where an average or bad one just knows they have to use it (and subsequently get stuck debugging pointers when they don't work as expected).

      --
      These posts express my own personal views, not those of my employer
    8. Re:I've become jaded by random0xff · · Score: 0

      Ok, so I get your point, but does it relate to this particular book?

    9. Re:I've become jaded by julesh · · Score: 2, Interesting

      It can take a week to make significant changes to a web page in Struts or Spring MVC, where it use to take about a day to do it for the clients developed with the RAD tools of the late 90s

      I have no experience of Struts, but if you have this problem with Spring MVC, you're using it wrong. Seriously. Spring MVC has helped me write some of the simplest, most maintainable web code I've ever worked with. Almost everything is automated: all I have to do in most situations for a common database view/query/update form is write a handful of lines of validation code, and usually a line or two of code to interact with a database access layer. The layout is produced in a GUI editor, and integration is a trivial matter of dropping tags in the right locations. Add a simple XML element to a config file and the page is integrated into the site and ready to work.

      Yes externalizing code into config files can make a system more flexible (but you'll pay for it in readability and tracability/debugability).

      If you're talking about Spring-style dependency injection, my experiences is that for almost any non-trivial code you'll more than gain anything you lose in readability or tracability in ease of writing unit tests.

      Yes aspects of the agile methodology - continual integration and test driven coding - can help but they're not the only way and there's a cost associated.

      Of course there's a cost. Writing code without tests is much faster than doing so with tests, but being confident that it's correct is the trick. Most of us aren't able to write correct code reliably, and the cost of delaying the fix to a bug until its picked out by testers (usually weeks or even months after the code is written) is normally substantially higher than writing unit tests at the same time as the code. And in my experience, writing tests first is faster than writing them immediately after: you get to think about your code design during the otherwise relatively easy stage of writing the test, so when you come to implement, you'll already have a fairly good idea of how to make the test pass. Test after often leaves me sitting, thinking about how to implement the feature, and then writing a mind-numbing test with just enough difficulty that I can't think about the next feature while I'm doing it.

    10. Re:I've become jaded by syousef · · Score: 1

      I have no experience of Struts, but if you have this problem with Spring MVC, you're using it wrong. Seriously. Spring MVC has helped me write some of the simplest, most maintainable web code I've ever worked with. Almost everything is automated: all I have to do in most situations for a common database view/query/update form is write a handful of lines of validation code, and usually a line or two of code to interact with a database access layer

      What are you using to automate? Do you have specific look and feel requirements from your users that violate the model you're working with? (eg. list views that save and also have details views that save). I don't get to choose the requirements. I also don't get to choose the tool unfortunately.

      If you're talking about Spring-style dependency injection, my experiences is that for almost any non-trivial code you'll more than gain anything you lose in readability or tracability in ease of writing unit tests.

      Have you ever tried an interactive debugger with injections? You have 2 options:
      1) Trace through lots of spring code that handles the injection
      2) Put a breakpoint at the entry point and treat it like magic.

      Of course there's a cost. Writing code without tests is much faster than doing so with tests, but being confident that it's correct is the trick. ...and you think a bunch of esoteric XML files, difficult to trace code, new language constructs and frameworks that are never allowed to mature before the next big thing comes along are the way to do this??? Please!

      Most of us aren't able to write correct code reliably

      So what are you telling me? That thanks to the magic of Spring your code is now bug free??? Or that your skills are so poor you require the latest and greatest language constructs and techniques to write something that works? I've never had problems writing correct code before these frameworks, but I've also never seen a complex system that was totally bug free.

      And in my experience, writing tests first is faster than writing them immediately after

      Again your experience is limited if your requirements never change and perfect tests can be written up front. What if you don't quite know how to solve a problem? In any complex system you're going to have some revision of the interface, and even more revision of the implementation, and that's before you get those requirements changes.

      Do you honestly think there's much new in these frameworks? If so you're either gullible or you're not being honest. I really wonder what kind of systems you work on that you can automate writing most of the code. I'm inclinded to be of the opinion that this is a religion and you're a defender of the faith. Pure and simple.

      --
      These posts express my own personal views, not those of my employer
    11. Re:I've become jaded by Anonymous Coward · · Score: 1, Informative

      I don't think K&R would be a good lecture book, but as a self study book it was excellent. It was the second computer book I'd read and by sitting down at the computer and working as I read I finished with a very solid understanding of C.

      I understand that it isn't what everyone needs, but that book has a good reputation for a reason.

    12. Re:I've become jaded by syousef · · Score: 1

      We'll just have to disagree on that.

      I think when it was written it was quite probably the best book out there and I can see how it would have been definitive for coding C under Unix. However I've seen many better books since. Things have moved on. K & R is neither easy to read nor engaging. I'd only use it as a secondary reference these days.

      --
      These posts express my own personal views, not those of my employer
    13. Re:I've become jaded by PybusJ · · Score: 1

      Mind you the blog site for the book that started going into detail about why Singleton (the most obvious fucking "pattern") is so "beautiful". I could have blown chunks right there. Effective and elegant if used correctly? Yes. A neat technique? Yes. Beautiful? Shit I almost spilled my coffee when I followed the link and saw that. However, when I read the whole blog posting it was about how Singleton might seem beautiful but is actually seductive and dangerous; much more sensible just dressed up with a somewhat trollish title.

      Mind you there was another post about the beauty of Java reflections that seemed to be serious!

      (Oh and I loved K&R when I learnt C from it, but then I was coming from a degree in Mathematics so it seemed like light relief)
  15. Bingo by Anonymous Coward · · Score: 0

    You've hit the nail on the head. If your code is too mysterious, it is usually easier to re-write from scratch than to modify it.

    For many years, all my code has been self-documenting. http://en.wikipedia.org/wiki/Self-documenting The result is that I can easily maintain the code and it's not too hard to find and re-use chunks of it. The joy of self-documenting code is that the code and the comments are maintained together.

    Even for embedded stuff, I usually find that it is well worth the effort to do a good job of commenting it.

  16. For 876344 by Anonymous Coward · · Score: 0

    87362 38726 88872 61726 67672 88872 13102 91228
    77798 77798 15882 13232 54060 54060 18577 00000

    1. Re:For 876344 by Tablizer · · Score: 1

      87362 38726 88872 61726 67672 88872 13102 91228
      77798 77798 15882 13232 54060 54060 18577 00000


      You fucktard! That string caused Windows to send an "I dump you" IM to my significant other.

  17. Dangers of binge drinking by ichigo+2.0 · · Score: 1

    There is a memory leak in your code. Or maybe it's a feature?

    1. Re:Dangers of binge drinking by another_fanboy · · Score: 1

      There is a memory leak in your code.

      Like everyone else I know, he cannot remember how many he's had. That way, he feels no regrets over having "just one more".

    2. Re:Dangers of binge drinking by Ungrounded+Lightning · · Score: 2, Funny

      There is a memory leak in your code. Or maybe it's a feature?

      Nope. drinkBeer(b) frees the beer instance.

      (But there may be a memory leak in the PROGRAMMER after enough iterations.)

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    3. Re:Dangers of binge drinking by julesh · · Score: 2, Funny

      There is a memory leak in your code. Or maybe it's a feature?

      getBeer() may be using the flyweight pattern, and reusing previous beer instances (presumably after their .urinate() method has been called to, err..., release them). This is clearly why the otherwise pointless typecast to (Beer) is present: the method probably returns Lager, and the writer wanted it to be clear that it was more generic than that.

    4. Re:Dangers of binge drinking by Misagon · · Score: 1

      It is even correct programmer lingo to say that drinkBeer(b) consumes the beer.

      --
      "We mustn't be caught by surprise by our own advancing technology" -- Aldous Huxley
  18. Then you're doing it wrong! by Anonymous Coward · · Score: 0

    If you have to update the comments every time, you're probably doing it wrong or your design changes a *lot* (in which case, why didn't you make better plans?).

    The comments should tell me *why* the code is doing what it's doing, not WHAT it's doing. I don't think anyone finds comments like this helpful:
    ++i; // Increments variable i by one

    However, comments like this may keep you from going crazy someday:
    float fastInvSqrt(float x) { /* Off by 1.5% at most. ~50 cycles faster than the more accurate version. */
    }

  19. But also read this by Anonymous Coward · · Score: 0
  20. Beautiful code by Anonymous Coward · · Score: 0

    Is the code that *I* write. Because I have half a chance of remembering what it does or is supposed to do.

    People think their clever when they abstract systems so much your left chasing down a seemingly bottomless call stack only to find
    all it does is i++;

    People think their doing you a service when they leave obvious comments that have long since become wrong and outdated. The overcommenting of their work makes what should be visible in one screen span 10 screens which *greatly* improves my understanding. At the same time they leave terse local comments inside large complex routines requring very specific domain knowledge.

    People think that using a goto statement *AND* leaving a comment specifically apologizing for its use somehow detracts from their own stupidity.

    People think that their saving time when they spend 10 minutes writing a code generator and proceed to cut and paste thousands of lines of eearily similiar code into *YOUR* project.

    People think that they should be quibbling with each other about use of indentions, braces...etc. My only response is 'jad -p' and a general sense of needing to find someone competent enough to run our HR department.

    People think its acceptable to use the source control system and code comments to carry on conversations with each other while manually reformatting each others code.

    At the end of the day your judged not on how beautiful your code is. Rather: Does it work, is it maintainable (v2,v3,v4..etc) and does it make the people who made the mistake of hiring you ***money***. If the answer is no to any of those questions then you suck.

    IE if it takes you 2 years to write beautiful correct code that is maintainable and works perfectly AND your project is two years late to market **you still suck**

  21. The most beautiful code I've ever seen... by element-o.p. · · Score: 4, Interesting

    ...looked like this:

    not exp log srand xor s qq qx xor
    s x x length uc ord and print chr
    ord for qw q join use sub tied qx
    xor eval xor print qq q q xor int
    eval lc q m cos and print chr ord
    for qw y abs ne open tied hex exp
    ref y m xor scalar srand print qq
    q q xor int eval lc qq y sqrt cos
    and print chr ord for qw x printf
    each return local x y or print qq
    s s and eval q s undef or oct xor
    time xor ref print chr int ord lc
    foreach qw y hex alarm chdir kill
    exec return y s gt sin sort split

    Simply elegant! My younger brother sent it to me; not sure where he got it. It's Perl, by the way.

    --
    MCSE? No, sir...I don't do Windows. Yes, I am an idealist. What's your point?
    1. Re:The most beautiful code I've ever seen... by Alaria+Phrozen · · Score: 1

      Yes it's pretty and balanced and such, and I bet you could convert it to music and it would be a fine jig, but... What does it do?

    2. Re:The most beautiful code I've ever seen... by Anonymous Coward · · Score: 3, Insightful

      prints "just another perl hacker"

    3. Re:The most beautiful code I've ever seen... by Anonymous Coward · · Score: 0

      That's the beauty of it. It doesn't do anything!

    4. Re:The most beautiful code I've ever seen... by skeeto · · Score: 1

      I think Brainfuck makes the most beautiful code of any language.

      +&gt;+&lt;
      [
      [-&gt;&gt;+&gt;+&lt;&lt;&lt;]&gt;&g t;&gt;
      [-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;
      [-&g t;+&gt;+&lt;&lt;]&gt;&gt;
      [-&lt;&lt;+&gt;&gt;]&lt ;&lt;
      ]

      This one, er... uh... calculates Fibonacci numbers. Don't tell me that that is not the most beautiful code you have ever parsed!

    5. Re:The most beautiful code I've ever seen... by skeeto · · Score: 1

      Sorry, that should read,

      +>+<
      [
      [->>+>+<<<]>>>
      [-<<<+>>>]<<
      [->+>+<<]>>
      [-<<+>>]<<
      ]
    6. Re:The most beautiful code I've ever seen... by Anonymous Coward · · Score: 2, Informative

      holy shit. as I copied that over to try it (uh, "in a vm", right), I noticed it's even better than you posted it! Here it is fixed-width:

      not exp log srand xor s qq qx xor
      s x x length uc ord and print chr
      ord for qw q join use sub tied qx
      xor eval xor print qq q q xor int
      eval lc q m cos and print chr ord
      for qw y abs ne open tied hex exp
      ref y m xor scalar srand print qq
      q q xor int eval lc qq y sqrt cos
      and print chr ord for qw x printf
      each return local x y or print qq
      s s and eval q s undef or oct xor
      time xor ref print chr int ord lc
      foreach qw y hex alarm chdir kill
      exec return y s gt sin sort split


      Now that's beauty!

    7. Re:The most beautiful code I've ever seen... by Alaria+Phrozen · · Score: 2, Funny

      No, that makes it retarded.

  22. Stupid frameworks. by mattgreen · · Score: 5, Insightful

    Ugh, Java frameworks.

    Somebody needs to drag the people who make these things in a room, erase their memories, and make them use what they have created. Perhaps then they can start to feel how asinine they can be sometimes. It is as if they get off on how many design patterns, random XML config files, and other "best practices" they can cram into a single framework. "We're switching to using a BuilderFactoryGatewayStrategyFacade." Thanks for the heads-up guys, we were all dying to know exactly how you implemented it! (Don't forget to scatter pattern names all over your code. People have to know you're using them!) All I want to do is integrate such and such framework in with my program. But, no, I have to read the documentation that describes the problem and how exactly to use the framework. Inevitably, they begin spouting off about how "elegant" it is that you can configure exactly which IntFactory to use by hard-coding the classname in a mandatory configuration file that is prone to getting lost at deployment time. (Remember, making objects with just the new operator is a classic beginner's mistake, don't fall prey!)

    The end result is you end up with what should be a fairly simple task (like OO-relational mapping) have 400 page manuals because it ends up doing every little thing that people want to do. In the time it takes you to choose the right framework, download and install the binaries, wade through the required config files, sift through the quickstart, and actually get familiar with how it is done, you could have just written and tested the tedious JDBC code to load and unload an object from the database.

    But, why do that? There's no hype around that! You're not REALLY an enterprise architect until you have twenty different config files that need to be present just to run your product! If it is an enterprise product, it shouldn't be simple to configure!

    All of these products do serve legitimate needs. But the obsessive over-engineering that surrounds them and the religious fervor by which they are declared Good (despite violating the principle of least surprise at every turn) point to fear. A fear that the code you're writing just isn't good enough somehow. The fear that your code is too simple, too straightforward. A worry that that requirement you're meeting is mission-critical, and, mishandled, could threaten the stability of the entire system. This isn't usually the case. It would seem that Java's simplicity sort of drives its hardcore users mad after awhile. What it lacks in expressiveness, people try to make up for by inane configuration and extensibility instead of just sitting down and Getting The Damn Thing Done. Sure, the code is boring. The best code is anything but glamorous.

    1. Re:Stupid frameworks. by Anonymous Coward · · Score: 0

      > what should be a fairly simple task (like OO-relational mapping)

      There's absolutely nothing simple about this. Especially when you're working with existing schemas.

      Oh, sure you *can* make it dead simple. And it will be dead slow.

    2. Re:Stupid frameworks. by mattgreen · · Score: 1

      Using existing schemas makes things more complicated sometimes. But don't even try to tell me that coding up the XML configuration file and setting up inheritance in Hibernate is somehow more intuitive than just doing it yourself with JDBC. If someone else had to support the raw JDBC code, they could at least step through what you wrote. This isn't quite the case with Hibernate, you just see the end result.

      Need to use multiple database vendors with one code base? Fine, use stored procedures, standard SQL, or abstract the difference away.

    3. Re:Stupid frameworks. by gatesvp · · Score: 1

      You know, this seems to work both ways. Ever worked with a homebrew framework that didn't have good exception-handling or some type of passable tracing? The other end of the spectrum from these IBM Java guys are the people who still hardcode strings everywhere in the system and hand-code ALL of their stored procs and data access layer.

      There are actually two problems here

      1. The Principle of Least Threshold
      2. Enterprise Hubris

      From the top, Javaheads like your above description are trapped in the Enterprise way of thinking. And hey they're building apps that will process more transactions in one day than many other small business apps will ever process. They have the right to be a little proud, the problem is that they're not very good at "scoping downwards". These frameworks all scaled up and came together, but now they have 400 pages of documentation and 12 different config files and everything is interdependent b/c they didn't want to lose functionality.

      Even written a good business logic layer (BLL)? Nor have I, nor have like 90%+ of programmers, but it's ok, most of them never need it. The BLL is just useless abstraction for the typical database front-end that we develop. BLL just gets smushed in with Entities and UI b/c it's pointlessly complicated to develop on all but the biggest systems.

      On the flip side, you get the Principle of Least Threshold, which is my term for the phenomenon where the perception of quality is limited by the highest level quality one has experienced. There are millions of small developers out there (VB 6 was the second most-used langauge at one point), who have never worked with any thing close to these monstruous Struts frameworks. So they don't understand them and they don't need half of the functionality and they can't spend 4 months figuring out how the system works, so they just build their own system one piece at a time and keep re-creating the parts of the wheel that they actually need.

      I'm living this, our Data Objects framework doesn't have tracing. Nobody cares but me, b/c I'm the only one who knows what a godsend it is to have instrumentation code. Just yesterday, wasted 2-3 hours diagnosing a problem that would've taken 10 minutes if we'd had minimal tracing (queries?).

      Of course, the real solution lies between the two camps. The Javaheads with the arcane infrastructure and architecture knowledge need to enable mechanisms to scale the complexity of their frameworks. The other guys need to start pushing from the other direction. But most of all the leaders in the field need to learn to embrace differences and change (man that sounds corny).

      When anyone starts spouting off about good software or bad software, they must at least identify the scale of the software with which they are working (and when was the last time we saw that). Unacceptable mistakes in an Enterprise Framework are just ignored in a 12-user system. In fact nearly every piece of code posted to the web is unacceptable in an Enterprise environment, b/c it fails to catch errors or instance tracing or define attributes or use fully qualified types or validate inputs or even comment in a way that is compatible with JavaDoc/NDoc/Sandcastle.

      A twenty line class in an Enterprise app could have 80 lines of associated "overhead code" that just plugs the class into the framework. Is this elegant and beautiful or just clunky and cumbersome? That answer could vary by system size, by programmer skill or even by personal taste. But no one seems to want to acknowledge this reality. The small guys call the Enterprise guys "clunky" and they in turn call the small guys "clumsy". So in the end they just ignore each other and throw rocks in each other's general direction and nobody stands and up and says "Hey guys, it's a continuum, it's not black and white, our solutions can only be inspirations for yours."

      We need new leaders. The guys in my CoDe & MSDN magazines aren't sitting around handing out three differ

    4. Re:Stupid frameworks. by cs02rm0 · · Score: 1

      iBATIS

      I find it like a halfway house between PreparedStatements and Hibernate. Works fine with existing schemas.

    5. Re:Stupid frameworks. by MythMoth · · Score: 2, Interesting

      The end result is you end up with what should be a fairly simple task (like OO-relational mapping) have 400 page manuals because... OR mapping frameworks require complex configuration only when you have to express complicated things about the relationships between the entities and the tables. There's no way to eliminate that without eliminating the relationship!

      Sensible OR mapping frameworks use sensible defaults, however, so that for simple classes simple configuration is required. For example, using Hibernate with a class with no associations with other classes, all you have to do is annotate it with @Entity and annotate the primary key property with @Id. Ooooh, tricky.

      In the time it takes you [...] you could have just written and tested the tedious JDBC code to load and unload an object from the database. That's just bollocks for anything except the most trivial of applications. If you have more than half a dozen entities and any even marginally complex relationships between them you'll save great big wadges of time by investing in learning the framework.

      Frameworks are great. People who use them often suck.
      --
      --- These are not words: wierd, genious, rediculous
    6. Re:Stupid frameworks. by julesh · · Score: 2, Interesting

      Need to use multiple database vendors with one code base? Fine, use stored procedures,

      AKA write multiple implementations, one for each vendor.

      standard SQL,

      AKA cripple your program to the lowest common denominator. You'll spend hours working around the fact that different vendors do even basic things like giving a record a unique identifier in different ways.

      or abstract the difference away.

      Which is precisely what frameworks like Hibernate do.

    7. Re:Stupid frameworks. by teknopurge · · Score: 1

      Use Icefaces and dump Struts.

      I've been where you are.

    8. Re:Stupid frameworks. by Anonymous+Brave+Guy · · Score: 1

      Frameworks are great. People who use them often suck.

      I disagree. Good frameworks are great when used in the context they were built for. Most frameworks I've encountered in my programming career aren't good, they're just overgrown libraries that aren't as flexible as they could be. Then those people-who-suck that you mentioned use those inflexible frameworks where they're not appropriate, and the result is a combination of huge amounts of boilerplate that wasn't really necessary and a whole load of truly clunky code just to work around the limitations in the framework.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    9. Re:Stupid frameworks. by bigtangringo · · Score: 1

      I can only speak with regard to Spring, as that's what I've used for the past two years. I'll give you that it has a moderately vicious learning curve, to use well. However, the vast majority of your configuration can be boilerplate stuff. I haven't worked much with JavaServer Faces, but I gave them up because it reminded me too much of ASP - using postbacks and JavaScript for every god damn thing in the world.

      I would also recommend against using Hibernate, ACEGI, and the various template languages if you can get along with JPA, JAAS, and JSP. ACEGI has got to be the most complicated, inelegant mess I've ever tried to work with. I think they've really sacrificed simplicity for flexibility.

      Spring as a whole is pretty damn good. Some of their features I'd never use, and seem excessive. I've been thinking about doing a series of articles to describe how to get a 3 tier web project up and going with Spring and JPA without going insane. Some things work really well under a 3 tier Java EE + Spring + JPA [+ JAAS] setup. Some things do not.

      Having developed primarily in Perl, PHP, and Java for several years each now I feel confident saying Java is well suited for large systems that you expect to grow. For a smaller system in which I don't anticipate much change in scope, I would recommend using PHP. Perl is my baby for 100% console applications or if I'm doing a lot of pattern matching and whatnot. If it's going to be a constantly running daemon that needs to be zippy, I'm going Java.

      Personally, I don't care about C or C++. The systems I work on do not need these extremes of speed, it makes more sense for me to complete the code significantly faster and get it into production. The speed differences in modern JVMs are to the point where my time is more valuable than the hardware to make up the difference. I think those languages are still good, just not well suited for the types of applications I work on.

      --
      Yes, I am a smart ass; it's better than the alternative.
    10. Re:Stupid frameworks. by syousef · · Score: 1

      Frameworks are great. People who use them often suck.

      Ah yes because if it's not simple and intuitive it's easier to say everyone sucks at coding than to build a framework that doesn't require a PhD to use correctly. Gotta love IT sometimes.

      --
      These posts express my own personal views, not those of my employer
    11. Re:Stupid frameworks. by syousef · · Score: 1

      You'll spend hours working around the fact that different vendors do even basic things like giving a record a unique identifier in different ways.

      That's called coding in the kitchen sink just in case. There may be good reasons to avoid using JDBC but differences in implementation between database vendors ain't one of them.

      Just how many enterprise systems have you worked on where the database vendor for the underlying schema has changed even once throughout its lifetime? I'm not talking about minor version upgrades but going from one vendor to another? Do you really think you could change to a different vendor without a complete re-test? The databases work differently enough that you'd be mad to try it. Chances are you'd need to tweak something (or more likely many things) in your code before you had something that behaved similarly.

      --
      These posts express my own personal views, not those of my employer
    12. Re:Stupid frameworks. by MythMoth · · Score: 1

      Ah yes because if it's not simple and intuitive it's easier to say everyone sucks at coding than to build a framework that doesn't require a PhD to use correctly. Feel free to build that ORM framework that doesn't require you to specify the mappings. It'll be slow and solve only the tiny subset of the problem that's easy to do without ORM anyway.
      --
      --- These are not words: wierd, genious, rediculous
    13. Re:Stupid frameworks. by syousef · · Score: 1

      On any given system you only need to solve a subset of the problem.

      The elitist attitude must make you one hell of a treasure to work with on a team.

      --
      These posts express my own personal views, not those of my employer
    14. Re:Stupid frameworks. by MythMoth · · Score: 1

      On any given system you only need to solve a subset of the problem. The elitist attitude must make you one hell of a treasure to work with on a team. Thanks for the ad hominem, but NIH won't earn you any friends either. If the framework is complicated it's probably because the problem domain is complicated. Maybe you should invest the time in understanding why it's complex.

      I've worked with all manner of hellish tangled incompetent and broken toy-implementations created by people who thought that a real grown-up framework was too difficult or over complicated. Feel free to roll your own, though - I earn a good living from fixing that kind of screw up.

      Hibernate is a particularly bad example for your case, because while the framework's implementation is certainly complicated (or dare I say it, sophisticated), the configuration complexity maps very closely to the complexity of the relationship between the entities and the database tables. I minimal mapped class looks like this:

      @Entity
      public class Foo {
        @Id
        public Long primaryKey;
      }
      Given that you have to say "I want this class to be persistent" and "I want this to be the primary key" it's hard to see how you could reduce that much even in your imaginary framework.
      --
      --- These are not words: wierd, genious, rediculous
  23. Visually and Logically Beautiful by MassEnergySpaceTime · · Score: 1

    I think there are two kinds of beauty in code: visual and logical. Visually beautiful code is code that is formatted well, easy to skim through, and easy to read. This includes things like defining useful variable/function names and writing understandable comments. Logically beautiful code is code that is designed to fit together well, makes a lot of sense, and leaves no confusion. It expresses its intent in the simplest and cleanest way possible.

    I think getting code to be logically beautiful is much harder of the two. It takes a lot of insight to see a simpler and cleaner way of expressing the same thing. To use a math analogy, a coder might get his code to work with this:

    F = (0.25 * m * x * a * 4) / x

    but not realize that it can be simplified to this:

    F = m * a

    You can teach people how to be visually beautiful with their code, but when it comes to logical beauty, they either have it, or they don't.

    --
    Respect the laws of physics, for the laws of physics have no respect for you.
    1. Re:Visually and Logically Beautiful by Breakfast+Pants · · Score: 3, Insightful

      That isn't true at all. What happens in the second case when x == 0.0 ?

      --

      --

      WHO ATE MY BREAKFAST PANTS?
    2. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      I'm not a professional programmer, and I have a physics degree not a CS degree, (and I have been drinking heavily) but to me it seems obvious that F is independent of x.

    3. Re:Visually and Logically Beautiful by PresidentEnder · · Score: 1

      I'm a math undergrad. Division by zero is always undefined, no matter how badly we want 0/0 to be 0.

      --
      I used to carry a bottle of whiskey for snake bite. And two snakes. -Nefarious Wheel
    4. Re:Visually and Logically Beautiful by Anonymous Coward · · Score: 0

      Well, you need to make a choice, do you want to break "anything divided by itself is 1" or do you want to break "0 over anything is 0". I think the first rule is better to keep, so 0/0 should = 1, and it's just not true that "0 over any denominator is 0". Over 0 it's 1.

    5. Re:Visually and Logically Beautiful by Anonymous Coward · · Score: 0

      With the more complex equation you will have to check for x==0 before executing it, because when x==0, F should be undefined.
      With the simplified equation, it seems to me that you still have to check for x==0 before executing it, because when x==0, F should still be undefined.

      if(x==0)
      //F is undefined
      else
      F = m * a;

      Having said that, I am debating a problem that I don't have all the information about. I don't know what x is.
      It is all too easy to assume that F=m*a refers to 'Force is Mass times Acceleration'.

      Take the formula for the circumference of a circle as an example: C=2r

      In Java, one could write any of the following:

      //A direct translation of the formula
      double c = 2 * Math.PI * r;

      //A direct translation of the formula with added readability
      double circumference = 2 * Math.PI * radius;

      //Refactoring out the constant parts of the expression may be a good idea when we need to repeat the formula with many different radius values
      double twoPI = 2 * Math.PI;
      double circumference = twoPI * radius;

      //Even this has advantages. Less operations at runtime. No references to the Math package can be good if you are a good mathematician but are new to Java.
      double c = 6.2831853071795 * r;

    6. Re:Visually and Logically Beautiful by Anonymous Coward · · Score: 1, Insightful

      What happens in the second case when x == 0.0 ?

      The program doesn't crash.

      If you want different behavior when x == 0, the appropriate way to do that is with a special case, not with sneaky notation. Trying to do otherwise will just make the code harder to read and introduce other unexpected behaviors. What happens when x is very large or inf or -inf or NaN? Are those behaviors intended or not?

    7. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      I guess I'm saying that the first equation is poorly formed - F is truly independent of x no matter how the equation is written. The first equation will cause *run-time problems* at x=0, but *mathematically* x=0 is irrelevant.

      If you are in a math class and someone tells you to graph y=x/x, you don't have a spike to infinity at x=0 or some sort of undefined region. You graph it as y=1. If you tried to code y=x/x without properly forming the equation you will get a runtime error when x = 0.

      You are honestly saying in a math class that you can't multiply either side of the equation F=ma by (x/x) without creating an undefined region at 0? You need to ask one of your professors about this if you think so.

    8. Re:Visually and Logically Beautiful by Anonymous+Brave+Guy · · Score: 1

      Amusingly, this whole thread actually supports the original poster's point: while everyone here is worrying about mathematical technicalities relating to the x/x, in reality it's almost certain that F=ma was what was needed, and the programmer who just wrote the clean version without introducing special cases never had these problems.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    9. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      >>Amusingly, this whole thread actually supports the original poster's point

      I agree.

      It is kind of disheartening though that people are "insightfully" rejecting the "beautiful code" because it does not have the same flaws as the poorly written, buggy code.

      Just to reiterate-

      There is no "special case". There is a bug in the 1st equation because it is poorly formed. The 2nd equation rewrites the code to remove the bug. The first equation requires an error handler to work properly. The bug is a result of poor programming - it is not a fundamental property of the math that needs to be duplicated to ensure that the equations are identical.

    10. Re:Visually and Logically Beautiful by Anonymous Coward · · Score: 0

      Uh, you have a physics degree and think that 0/0 is infinity or one??? It's neither! It is an indeterminate form.

    11. Re:Visually and Logically Beautiful by mcmonkey · · Score: 1

      There is no "special case". There is a bug in the 1st equation because it is poorly formed. The 2nd equation rewrites the code to remove the bug. The first equation requires an error handler to work properly. The bug is a result of poor programming - it is not a fundamental property of the math that needs to be duplicated to ensure that the equations are identical.

      I think you're all missing the point. The point is, programs are just tools. The beautiful tools are in harmony with their purpose. The beautiful hammer would be one such that, from just the hammer and the nail, it is impossible to deduce whether the hammer was designed to drive the nail or the nail was designed to be driven by the hammer.

      For "F=ma" vs "F=mxa/x": what is the purpose? Perhaps the design was for an expression of force equals mass times accelerate, with the special case of no meaningful calculation of force when x=0. In that case, "F=ma" would not be correct tool. Or perhaps the purpose is to calculate force without consideration of the value of x. In either case, you cannot evaluate the beauty/usefulness/correctness of any program without an understanding of the purpose.

      Code isn't done when there is nothing left to add. Code is done when there is nothing left to take away.

    12. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      >>Uh, you have a physics degree and think that 0/0 is infinity or one??? It's neither! It is an indeterminate form.

      I'm not really addressing 0/0 directly - everybody else is trying to make it about that. I'm saying that in equation form, x/x = 1. Mathematically I'm saying that F=ma=max/x, but people are trying to argue that F=ma=max/x iff x 0. I'm utilizing 8th grade algebra here, but since I appear to be in the minority maybe there is some higher math going on that I do not understand.

    13. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      I see what you are saying, but I still think F=mxa/x is bad code even for the special case you describe because you still have to test for x=0. // If x0 then F=ma else DoThis // There is no point in including it in the equation that I can see. Including it in the equation just makes it look like a poorly formed equation. If you want something else special to happen when x=0, this should be made explicitly clear since it defies basic math.

    14. Re:Visually and Logically Beautiful by MontyApollo · · Score: 1

      ...doesn't like "left-bracket right-bracket" even in plain text...

      If x!=0 then F=ma else DoThis //Hey Something Special Here!

    15. Re:Visually and Logically Beautiful by PresidentEnder · · Score: 1

      You don't have a spike to infinity, you have a point discontinuity, which you indicate on the graph if it is important.

      --
      I used to carry a bottle of whiskey for snake bite. And two snakes. -Nefarious Wheel
    16. Re:Visually and Logically Beautiful by DragonWriter · · Score: 1

      Division by zero is always undefined, no matter how badly we want 0/0 to be 0.


      Actually, in this case, I think the previous poster wanted 0/0 = 1, not 0.

      And, IIRC, division by zero isn't always undefined, its just always not a real number. I think 0/0 is still undefined, though I could be mistaken.
  24. People hate my returns. by Javagator · · Score: 1

    I usually put the loops in a method and do it like this.  People don't like my returns in the middle of a loop either.

    for (loop 1)
    {  for (loop 2)
       { if (some condition)
         {  return;
         }
         do work;
       }
    }

    1. Re:People hate my returns. by krischik · · Score: 1

      You know, I consider that worth then goto. Unlike BASIC modern goto always comes with a label. When reading the code that doubles the changes to notice the jump. See:

      http://en.wikibooks.org/wiki/Ada_Programming/Contr ol#Isn.27t_goto_evil.3F

      Martin

  25. Obligatory comment that 90% of programmers' by ClosedSource · · Score: 1

    code sucks but I (and the 90% of programmers who make this claim) are in the remaining elite 10% that are coding Gods.

    1. Re:Obligatory comment that 90% of programmers' by grahamd0 · · Score: 1

      The 10% aren't the people who write the prettiest code, they're the people who open other people's minds and create new paradigms.

      I think most of us in the 90% know that most code (including ours) sucks at least a little bit.

      Any competent programmer can write elegant and well commented code, but in the real world it rarely survives contact with ambitious deadlines and the whims of the client.

      My code works, I get paid, and that's good enough for me.

    2. Re:Obligatory comment that 90% of programmers' by ClosedSource · · Score: 1

      I agree that nobody is perfect. I was just mocking the daily WTF mentality. The real software crisis has more to do with ego than with the quality of code.

    3. Re:Obligatory comment that 90% of programmers' by julesh · · Score: 1

      code sucks but I (and the 90% of programmers who make this claim) are in the remaining elite 10% that are coding Gods.

      However you (unlike me) are not in the elite 10% of English-speakers who know how to use paranthetical phrases correctly.

    4. Re:Obligatory comment that 90% of programmers' by guitaristx · · Score: 1

      Apparently "coding Gods" am bad at grammar.

      --
      I pity the foo that isn't metasyntactic
    5. Re:Obligatory comment that 90% of programmers' by ClosedSource · · Score: 1

      Given the fact that I was mocking the whole "coding Gods" idea, any grammar mistakes I made are ironically appropriate.

  26. No. That is not a trick, that's doom. by Uksi · · Score: 1

    When you're done designing your application in a way that it will grow gracefully and stay beautifully, come see me, because you'll be out of a job for not shipping the product on time.

    You say that knowing the future requirements is difficult. That's the key insight: you just don't know. And unless you know, or have a good likely-to-happen general idea, you should not design it in any way other than as simple as it needs to be for right now. And if you guess, you are likely to end up with flexibility in all the wrong places.

    The trick is to design simple for what you need now (easy), and then be able to expand your design to stay simple (hard).

    This is difficult to accomplish because changing existing code is a no-no in software dev corps. "If it ain't broke, don't fix it" mentality dooms your project and causes you to accumulate massive design debt because of the hacks and not-simple solutions that do not touch existing code.

    This design debt grows to mountain proportions, at which point everyone throws their hands up and assert that a complete rewrite is required.

    The cure is to perform test-driven development, so that you are not afraid to change existing code. I can't emphasize how liberating it is to be able to come in and uproot some inflexible crap (which was good enough for a long time, but is not anymore), put in an improved design, and then know that you didn't break anything. You can roll with the punches and not waste your time designing in unnecessary flexibility.

    1. Re:No. That is not a trick, that's doom. by Uksi · · Score: 1

      I wanted to add that this is why many people become jaded in one direction or another.

      For myself, the learning curve went something like this:

      1) Was tight on time, decided to copy/paste code and not design in flexibility for things I thought could probably use it. Ended up taking more time than I probably would have otherwise and turning out some poor inflexible code. At this point, I swore to design everything up-front first.

      2) Next time around decided that I will design, design and design. End up spending a ton of time designing with all sorts of flexibility in place, so much time that the project never got finished or really gotten anywhere. At this point, I am scarred and have no idea what the right answer is.

      3) Spend the rest of the time being afraid of underdesign, and yet also being afraid of overdesign. Due to time pressure, was afraid to revisit poor design decisions (poor in retrospect), and end up churning out mediocre code that you see in your everyday company.

      This is where most programmers are. They know that underdesign is bad and they can't spend all the time overdesigning, so anything that gives the impression of either is bad, even if it's the right thing. Under time pressure, most people gravitate into underdesign, writing hacky code and never coming back around to fix it.

    2. Re:No. That is not a trick, that's doom. by mgblst · · Score: 1

      As with most things in life, the answer is to not take things to extreme. Allocate a reasonable amount of time for the design stage, and stick to it. Or do a simple design first, and add to it.

    3. Re:No. That is not a trick, that's doom. by Anonymous+Brave+Guy · · Score: 1

      The cure is to perform test-driven development, so that you are not afraid to change existing code. I can't emphasize how liberating it is to be able to come in and uproot some inflexible crap (which was good enough for a long time, but is not anymore), put in an improved design, and then know that you didn't break anything. You can roll with the punches and not waste your time designing in unnecessary flexibility.

      Unfortunately, you appear to make the same honest mistake as most TDD advocates I have encountered: you sincerely believe that having a good test suite automatically makes it safe to go in and change code. How do you know your tests really cover all the important behaviour? What if it's not practical to model all the possible scenarios your code has to cope with separately, for example because there are an effectively infinite number of them? A reasonably large software project may have 10k decision points. How many of those projects have test suites containing the millions of test cases that will typically be needed to test all execution paths independently? Even then, with around 10^3010 theoretical possibilities, how do you know you really got all the paths that are possible given the dependencies in the code?

      Automated tests are, in general, a good thing. Refactoring to maintain a clean code base is, in general, a good thing. But automated unit tests are only one way you try to keep your code working properly, and having a test suite is no substitute for understanding how the code works before your change it. Small-scale refactoring — as typically advocated by TDD supporters, though I recognise that you didn't write this explicitly yourself — is no substitute for maintaining a coherent overall design: it may lead to local maxima in code quality, but after a while if there are significant changes in the system requirements due to new features, you might just be taking careful, small steps towards a dead end, when you should have back-tracked and gone around.

      The trick is to know when to make small, incremental changes to the code, and when it's worth taking a step back and perhaps adopting a new approach or rewriting a larger section more generically. Both having automated tests and having a clean design in the existing code will help you to make such decisions and to implement them as safely as possible, but they do not guarantee it.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    4. Re:No. That is not a trick, that's doom. by Uksi · · Score: 1

      As you have noticed, I never claimed to limit the refactoring to a small-scale. You're right that large-scale refactoring or a new approach is often the right solution, and, when you're at that point, it's often a most helpful approach. However, it's exactly at that point that typical software management throws up their hands and says we ain't gonna touch existing code.

      And so the other part is that I never mentioned restricting testing to developer/unit tests only. Having full integration/functional tests is essential as well. These tests require nontrivial infrastructure (specific setups and test beds), and also take much much longer to execute. However, they tend to be significantly more static and are the key to helping you ensure success of large-scale refactorings.

  27. Sissy Boys by Anonymous Coward · · Score: 0

    Real men code in assembler to boot the system for the rest of you nancies.

  28. My Beautiful Code by cjjjer · · Score: 1

    10 PRINT "Hello World"
    20 GOTO 10
    1. Re:My Beautiful Code by Anonymous Coward · · Score: 0

      I prefer:

      10 ? "hello world" : goto 10

      sorry, couldn't resist!

  29. Poetic Code by klenwell · · Score: 2, Interesting

    I purchased the book after reading this recent slashdot thread, where I believe Mr. O' Reilly mentioned it himself. My degrees are literature and poetry, so I probably have a slightly different aesthetic than most programmers. I'm leisurely working my way through the book and enjoying it. Most the examples provided don't strike me as breathtakingly beautiful so much as intelligent solutions to interesting problems.

    One example I do find beautiful, after reading some of the explications of it, was this one mentioned a while back on slashdot:

    Origin of Quake3's Fast InvSqrt()

    I also find the algorithm here beautiful insofar as it elegantly solves a challenging problem that I was working on commonly faced by accountants:

    http://www.geocities.com/SiliconValley/Garage/3323 /aat/a_diop.html#diophant

    By the way, for truly poetic code, see the works of Kay Ryan. Or Spenser's Faerie Queene.

    --
    Innovation makes enemies of all those who prospered under the old regime... -- Machiavelli
  30. You can do this using tail calls in Scheme. by Estanislao+Mart�nez · · Score: 1

    If you're still writing C in 2007, I guess you're kind of stuck: the language provides no syntactic abstraction. so hacks like that are ubiquitous.

    It's the same in pretty much every mainstream language out there. You've hit one nail in the head when you point out the lack of syntactic abstraction problem. There's a couple of additional lack of abstraction problems, though: you can't use functions as values, which is another way of abstracting looping logic, using higher order functions like map or filter; also, the language doesn't provide high-level flow control, like combinations or such.

    I usually program in Scheme, and I suspect that the way I'd do whatever GP is doing is by using explicit continuation-passing style. The functions in question would take as an argument a function that does the thing that's supposed to happen when the condition fails: the "failure continunation." Then you do your looping using tail recursion:

    ((define (outer-loop loop-state failure-continuation)
    ;; The failure-continuation argument is just a function that gets
    ;; called if the condition that breaks the loop is met.
    (if (end-condition? loop-state)
    loop-state
    ;; The function inner-loop will call us back in tail position.
    ;; Since tail calls compile down to gotos, this will be the same
    ;; native code as any low-level loop.
    (inner-loop loop-state failure-continuation)))

    (define (inner-loop loop-state failure-continuation)
    (cond ((end-condition? loop-state)
    ;; If we come to the condition that ends the inner loop, we
    ;; tail-call the outer loop (our "success continuation")
    (outer-loop loop-state failure-continuation))
    ((break-condition? loop-state)
    ;; If the break condition is met, we just call the failure
    ;; continuation, which "exits the loop." Since this is a
    ;; tail-call, again, this compiles down to a goto into the
    ;; code for failure-continuation
    (failure-continuation loop-state))
    (else
    ;; If neither condition is met, then we just use tail
    ;; recursion to loop.
    (inner-loop (produce-next-state loop-state)))))

    Yeah, the word "continuation" sounds scary, but this is not using call-with-current-continuation or anything that complicated. All you're doing is using tail call optimization to implement the nested loops and the break with nothing other than conditionals and tail calls.

    1. Re:You can do this using tail calls in Scheme. by Anonymous Coward · · Score: 0

      I've been a Common Lisp programmer too long, so either I don't get the joke, or I don't see how that's not insanely over-complex. Conceptually it's not that hard, but it looks like a lot of code for such a simple task.

      In CL I'd say:


      (loop named outer ...
          (loop ...
              (if (...) (return-from outer my-value))
      ...))


      and it's all macros so it gets compiled into GOTOs at the machine level.

      (Then again, a Scheme programmer would probably say that the loop macro itself is insanely over-complex. Touche. It's so durned practical, though.)

  31. Properly indented code for that by Estanislao+Mart�nez · · Score: 1

    (define (outer-loop loop-state failure-continuation)
      ;; The failure-continuation argument is just a function that gets
      ;; called if the condition that breaks the loop is met.
      (if (end-condition? loop-state)
          loop-state
          ;; The function inner-loop will call us back in tail position.
          ;; Since tail calls compile down to gotos, this will be the same
          ;; native code as any low-level loop.
          (inner-loop loop-state failure-continuation)))

    (define (inner-loop loop-state failure-continuation)
      (cond ((end-condition? loop-state)
             ;; If we come to the condition that ends the inner loop, we
             ;; tail-call the outer loop (our "success continuation")
             (outer-loop loop-state failure-continuation))
            ((break-condition? loop-state)
             ;; If the break condition is met, we just call the failure
             ;; continuation, which "exits the loop."  Since this is a
             ;; tail-call, again, this compiles down to a goto into the
             ;; code for failure-continuation
             (failure-continuation loop-state))
            (else
             ;; If neither condition is met, then we just use tail
             ;; recursion to loop.
             (inner-loop (produce-next-state loop-state)))))

  32. Re:Cool. You just wrote a bug. by maglor_83 · · Score: 1

    If you were using python, you could do something like:

    while not wannabreak:
       for j in range(0, jmax):
          # inner loop
          if wannabreak:
             break
       else:
          # outer loop

    But really, breaks are worse than a goto used in this context anyway.
    A break is just a goto without an easy to find label, so the goto makes
    it easier to read.

  33. Re:Cool. You just wrote a bug. by fbjon · · Score: 1

    But really, breaks are worse than a goto used in this context anyway. A break is just a goto without an easy to find label, so the goto makes it easier to read. I don't think so. A break is clearly defined, there's no ambiguity over where control will go, while goto requires a separate dangling label that can become misplaced, deleted, etc.

    It's the same as initialising some counter before a while-loop: moving the loop without the initialiser breaks the code, so that's why you use a for-loop for those instead, which keeps things tidy.

    --
    True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
  34. Break from inner loops by krischik · · Score: 1

    But you only need a goto because your programmig language can not break out of inner loop. See:

    http://en.wikibooks.org/wiki/Ada_Programming/Contr ol#loop_with_condition_in_the_middle

    As you can see in Ada loops have (optional) names and with that name the exit statement can break from any lool no matter how deeply nested they are.

    But if I where to use a lesser language like C or C++ I would do it the very same way - just use a goto.

    Martin

  35. OS by u235meltdown · · Score: 1

    ["Beautiful Code" features 33 different case studies about challenging coding scenarios from some of today's most high-profile developers and OS project leaders.]

    OS as in Open Source or Operating System...
    obviously the first, but still.. quite ambiguous.

  36. Java - nah by bytesex · · Score: 1

    This site's primary concern seems to be java. Like the GOF, they seem to want to monopolize what is good and beautiful about it and most of all, how to do it. All fine and dandy if you're looking at ambitious eighteen year olds (ambitious to become faceless programmer droids, that is), but there seems to be an awful lack of discussion going on. Besides, currently my concern in _not_ java - so tell me again why this site would bother me ?

    --
    Religion is what happens when nature strikes and groupthink goes wrong.
    1. Re:Java - nah by julesh · · Score: 2, Informative

      This site's primary concern seems to be java

      Huh? Are you looking at the same site as me? I count 10 articles, of which:

      1 is about the design of a core Java API
      1 is about implementing a library in C
      3 are completely language independent
      1 is about a development environment called "Subtext" which has its own language
      1 is about Haskell
      1 is about the book discussed
      2 are about object-oriented design, and use Java in example code (but the text of the article applies equally to any object-oriented language)

      That doesn't seem to be particularly Java-focussed to me.

    2. Re:Java - nah by bytesex · · Score: 1

      *looks again* yup, you're right. I suppose I was just being cranky; that Singleton example ticked me off.

      --
      Religion is what happens when nature strikes and groupthink goes wrong.
  37. We all use goto, we just call it something else by Anonymous+Brave+Guy · · Score: 3, Interesting

    Which is presumably why languages like Pascal, Java, Python, Ruby, etc. all support goto.

    But how many of the above languages support...

    • early function return?
    • exceptions?
    • break/continue/last/next escapes within loops?

    goto is like assembly language: it's a flexible tool, but very primitive. Just as higher level languages are more expressive than assembly, meaning we rarely have reason to write raw assembly any more, so higher level languages have developed more expressive versions of goto, meaning we rarely have to write a raw goto any more.

    I think someone needs to write a new article, called “Dogmatic structured programming considered harmful”. While block structure with the sequence, iteration and decision operations has proven a useful model for describing algorithms, other powerful abstractions for control and data flow exist. Functional programming tends to use recursion rather than iteration, for example, and many functional languages don't really model sequence in the classical sense either. Almost all modern, general purpose programming languages support the concept of exceptions, which are just a more systematic form of goto. In some programming languages, there is no explicit concept of control flow at all.

    I don't see many people who understand these extended or alternative models complaining about how we should go back to doing everything with block-structured, procedural code. We just have to learn to use different models effectively, as functional programmers found before they realised the importance of tail recursion, as OO programmers found before they learned to control stack unwinding. This is called “progress”, and is what happens with experience... unless you adhere dogmatically to the way things are done at the moment, regardless of any objective merit an alternative may have.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  38. Re:Cool. You just wrote a bug. by morgan_greywolf · · Score: 1

    Heh. You're right, I did. As others have pointed, out a break is really the best.

    And we're initializing counters for while loops cause he wanted to use a for. You generally need a for when you want to run something n number of times. A while controlled by a counter does the same thing.

    And as for whether I write avionics or life support software: hey, look, it's Slashdot, here. I wrote that post in under 30 seconds. What do you expect? But, as it were, I don't write such software...I just write stupid little applets in Python for doing things like controlling printers, but you could probably tell that from my link. ;)

  39. Yuk by ET_Fleshy · · Score: 1
    Found in the examples:

    if (/GET \/ongoing\/When\/\d\d\dx\/(\d\d\d\d\/\d\d\/\d\d\/[ ^ .]+) /)
    Okay, how in the hell is that "beautifull?"

    if ($_ =~ m|GET /ongoing/When/\d{3}x/(\d{4}/\d{2}/\d{2}/[^ .]+) |)
    1. Re:Yuk by Anonymous Coward · · Score: 0

      For me, it would be the fact that the second line is clearer on its intent than the first. Even though they do the same thing, the latter snippet uses different parts of Perl to reduce escaping (syntactic noise in this case), reduce the regular expression to a more maintainable beast, and explicitly shows the use of the default buffer ($_).
      Granted, I might not categorize this particular example as "beautiful code", but you can certainly say there is a (significant?) improvement in the latter's approach.

    2. Re:Yuk by ET_Fleshy · · Score: 1

      Sorry, I should have definitely made myself more clear on that post! The first part was the "beautiful code" that we provided in one of the examples. The latter was me fixing it.

      Never have I seen of a love for slashies greater than those farkers over at Fark.com

    3. Re:Yuk by Anonymous Coward · · Score: 0

      Wow, they advocate beautiful code and don't employ standard techniques to make their own examples clearer? I had read some of the postings on the main page, but didn't delve into any of their articles. My bad :-).

      That changes my opinion of their potential value. It's real tough to accept a stranger's viewpoint on something as abstract as "clean design" and "beautiful code" to begin with, and even more so if the examples given don't adhere (even closely!) to what practitioners of the trade would expect.

      Ah well, I guess this is yet another site to write off which had a nice idea, yet fell short in delivery.

  40. Truly beautiful by zolaar · · Score: 1

    The most beautiful code in the world is that block of code that finally gets the shit to compile and build yes yes yes ohhhh thank you thank you god i can go home now wait hold it jesus fuck fucking wait what time is it the clock says its wednesday i thought it was tuesday fucking shit whatever oh shit oh shit shit shit oh shit i didn't call julie again shit shit shit shit shit well thats fucking great ive been here for the last 46 hours and now im finally able to go home to my pissed off wife who will ultimately deny me sex again and make me sleep on the goddamn couch like a goddamn dog. fucking beautiful.

    --
    One man's constant is another man's variable.
  41. Let the code speak for itself by heinzkunz · · Score: 1

    Variables and functions can have names, and they should be meaningful. There are functions, classes, etc. to divide code into manageable parts. A part should do only one thing and do it well. Put parts with similar function in a group with a proper name. This is called self documenting code

    Use comments to explain non-obvious solutions to a problem, for example if you had to work around a bug in an external library. Don't explain in a comment what is already concisely expressed in code.

    Document interfaces. If you want other programmers to use your code, you should document the classes and functions they call. This will save them a lot of time and make your code more valuable, but it's a rather boring task. Not every project has such an interface.

  42. Re:atari 2600 by ClosedSource · · Score: 1

    Atari games contain very ugly code, but how many people can say they wrote code that sold over 100,000 units at a penny per byte?

  43. One word: db4o by master_p · · Score: 1

    It may sound like an advertisement, but db4o (www.db4o.com) is so simple that puts Hibernate to shame. All you have to do is ...save your objects in the database. Your objects is the schema. It's amazing. And it has no external config files!

  44. mathematician vs. physicist by Crispy+Critters · · Score: 2, Interesting
    "Division by zero is always undefined"

    Unlike mathematicians, physicists almost never distinguish between "f(x0) equals y" and "the limit of f(x) as x approaches x0 is y." (I am not saying that there are no cases where the distinction is made, e.g. degeneracies in QM.)

    You'd be amazed at the hideous things physicists do with the Dirac delta function.

  45. OpenSSL by pppppppman · · Score: 1

    I've tried writing code using OpenSSL's libraries recently, I tell you it's horrible.

    First off, their documentation on their site is permanently marked [STILL INCOMPLETE]; this meens the most I can do with their documentation is connect to some host using SSL/TLS, read/write, and close. I can't check any certificates or anything. I check their documentation that was download with the source code, and it's all in some foreign .pod format I had to google for.

    So I gave up on that, and I thought looking at their code directly would be a good idea. No, it wasn't.

    Check this one out:

    static int do_cmd(LHASH *prog, int argc, char *argv[])
    {
    FUNCTION f,*fp;
    int i,ret=1,tp,nl;

    if ((argc <= 0) || (argv[0] == NULL))
    { ret=0; goto end; }
    ...

    where the end label stipulates:

    end:
    return(ret);
    }



    Why have ret=0; goto end; at all? They have it on one line to begin with, they could make it one statement with return 0.
    And no-where in this badly indented, spaghetti code is their useful comments/documentation (ok, now that I had a good look, I see there is a function or two that has a comment or two).

  46. I am absolutely not kidding. by Estanislao+Mart�nez · · Score: 1

    The whole problem with putting a return statement in the middle of a function is that when you do so, you actually have to read the code carefully to figure out what the control flow is. Try reading code in a language without return statements: you can figure out the control flow much faster, just from the syntax of the code you're reading. (Lisp variants are pretty good in this regard, as are most functional languages.)

    1. Re:I am absolutely not kidding. by bensch128 · · Score: 1

      I agree that returns in the middle of a method are not pretty but at least it won't lead to undefined errors.

      Since I've been programming C++ mostly, I try to use returns only in the beginning or end of a method. I like to be able to do verification and escape early rather then have lots of indentation.

      cheers
      ben