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."

56 of 286 comments (clear)

  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 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.
  2. 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 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 ?
    4. 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.
    5. 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.
    6. 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. :)
  3. 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 ?

  4. 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: 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++
      }

    2. 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
    3. 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).

    4. 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.

    5. 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
      }

    6. 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.

    7. 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.

    8. 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
    9. 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.
    10. 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
    11. 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).

  5. 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.

  6. 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.

  7. 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.

  8. 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.
  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 Anonymous Coward · · Score: 2, Funny

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

  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.

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

    http://xkcd.com/292/

    That is all.

  12. 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: 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
    3. 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.

  13. 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.

  14. 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 Anonymous Coward · · Score: 3, Insightful

      prints "just another perl hacker"

    2. 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!

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

      No, that makes it retarded.

  15. 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 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
    2. 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.

  16. 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?
  17. 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
  18. 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
  19. 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
  20. 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.

  21. 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.

  22. 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.
  23. 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.