Forgot your password?
typodupeerror
Programming IT Technology

Beautiful Code Interview 286

Posted by ScuttleMonkey
from the painting-with-text dept.
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."
This discussion has been archived. No new comments can be posted.

Beautiful Code Interview

Comments Filter:
  • by AuMatar (183847) on Wednesday August 08, 2007 @06:51PM (#20163475)
    Yeah, thats about the amount of beautiful code I expect to see in my life time.
  • by Anonymous Coward on Wednesday August 08, 2007 @07:04PM (#20163583)
    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"
    • Re: (Score:2, Funny)

      And to think if he posted it on Slashdot, he might've actually gotten a +5 Funny! ;)
    • by mrchaotica (681592) * on Wednesday August 08, 2007 @08:13PM (#20164199)

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

      • Re: (Score:3, Interesting)

        by dargaud (518470)
        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.
        • Re: (Score:3, Interesting)

          by stdarg (456557)
          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
  • by Anonymous Coward on Wednesday August 08, 2007 @07:05PM (#20163591)
    If you haven't looked at it already, you should glance through the OpenBSD [openbsd.org] source code [openbsd.org]. 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.

    • Re: (Score:3, Informative)

      by Anonymous Coward
      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 b

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

    • by garett_spencley (193892) on Wednesday August 08, 2007 @08:33PM (#20164377) Journal
      Hey Theo ... haven't chatted with you in a while. How's it going ? Family doing well ?
  • 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:

    • by jbellis (142590)
      fortunately newer languages solve this with labeled loops and break <label> and continue <label>; no goto needed.
      • 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.
        • Re: (Score:3, 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 c
          • Re: (Score:3, Informative)

            by Jaime2 (824950)
            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.
        • by Crispy Critters (226798) on Wednesday August 08, 2007 @09:08PM (#20164639)
          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.

          • Re: (Score:3, Interesting)

            by renoX (11677)
            [[ 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
        • Re: (Score:3, Insightful)

          by gfody (514448)

          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.
    • Re: (Score:2, Insightful)

      by RootsLINUX (854452)
      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();
      }
    • by Anonymous Coward on Wednesday August 08, 2007 @07:38PM (#20163915)
      http://xkcd.com/292/ [xkcd.com]

      That is all.
    • 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;
         }
      }
    • by a.d.trick (894813)
      ever thought of using functions and a return?
    • by Plutonite (999141)
      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
    • by matvei (568098)
      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. ;-)
    • 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.
  • by BlueBoxSW.com (745855) on Wednesday August 08, 2007 @07:19PM (#20163729) Homepage
    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
     
  • by lottameez (816335) on Wednesday August 08, 2007 @07:29PM (#20163833)
    while (1){
    Beer b = (Beer)getBeer();
    drinkBeer(b);
    belch(BelchType.LOUDLY);
    }
    • Re: (Score:2, Funny)

      by RetroGeek (206522)
      You forgot to add inside the loop:

      Bladder blad = Bladder.getInstance();
      if ( blad.isHurting() )
      {
        bld.empty();
      }
    • It's times like this I wish you could moderate +1 Sexy
    • There is a memory leak in your code. Or maybe it's a feature?
      • Re: (Score:3, 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.)
      • Re: (Score:3, Funny)

        by julesh (229690)
        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.
    • Re: (Score:2, Funny)

      by Anonymous Coward
      Let us pray getBeer() does not return a Singleton.
  • by intx13 (808988) on Wednesday August 08, 2007 @07:33PM (#20163861) Homepage
    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.
    • 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
    • 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
      • by Uksi (68751)
        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
  • I've become jaded (Score:5, Insightful)

    by syousef (465911) on Wednesday August 08, 2007 @07:48PM (#20163989) Journal
    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.
    • Re: (Score:2, Insightful)

      by RetroGeek (206522)
      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.
      • by syousef (465911)
        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!
    • 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.

    • Stupid frameworks. (Score:5, Insightful)

      by mattgreen (701203) on Wednesday August 08, 2007 @08:48PM (#20164481)
      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.
      • by gatesvp (957062)

        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

      • Re: (Score:3, Interesting)

        by MythMoth (73648)

        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

    • 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 ;)
      • Re: (Score:3, Interesting)

        by syousef (465911)
        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 compute
    • Re: (Score:3, Interesting)

      by julesh (229690)
      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/updat
  • by element-o.p. (939033) on Wednesday August 08, 2007 @08:40PM (#20164425) Homepage
    ...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.
    • Re: (Score:2, Informative)

      by Anonymous Coward
      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 r
  • 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 harde
  • code sucks but I (and the 90% of programmers who make this claim) are in the remaining elite 10% that are coding Gods.
  • Poetic Code (Score:3, Interesting)

    by klenwell (960296) <klenwell@gmail.cCOUGARom minus cat> on Wednesday August 08, 2007 @11:57PM (#20165745) Homepage Journal
    I purchased the book after reading this recent slashdot thread [slashdot.org], 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() [slashdot.org]

    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 [geocities.com]

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

: is not an identifier

Working...