Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Beautiful Code Interview 286

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 morgan_greywolf ( 835522 ) on Wednesday August 08, 2007 @07:18PM (#20163717) Homepage Journal
    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++
    }

  • Re:Have to say... (Score:4, Interesting)

    by kevin_conaway ( 585204 ) on Wednesday August 08, 2007 @07:21PM (#20163755) Homepage

    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.

  • Beautiful Code (Score:0, Interesting)

    by Anonymous Coward on Wednesday August 08, 2007 @07:35PM (#20163879)
    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.
  • Re:Have to say... (Score:3, Interesting)

    by kevin_conaway ( 585204 ) on Wednesday August 08, 2007 @08:01PM (#20164089) Homepage

    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.

  • by garett_spencley ( 193892 ) on Wednesday August 08, 2007 @08:03PM (#20164111) Journal
    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).
  • by garett_spencley ( 193892 ) on Wednesday August 08, 2007 @08:13PM (#20164203) Journal
    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.
  • 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.
  • Poetic Code (Score:3, Interesting)

    by klenwell ( 960296 ) <klenwell@nospaM.gmail.com> 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.
  • Re:I've become jaded (Score:3, Interesting)

    by syousef ( 465911 ) on Thursday August 09, 2007 @12:36AM (#20165989) Journal
    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).

  • Re:I've become jaded (Score:3, Interesting)

    by julesh ( 229690 ) on Thursday August 09, 2007 @05:16AM (#20167175)
    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.
  • by MythMoth ( 73648 ) on Thursday August 09, 2007 @05:18AM (#20167185) Homepage

    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.
  • by julesh ( 229690 ) on Thursday August 09, 2007 @06:26AM (#20167511)
    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.
  • by Bill Dog ( 726542 ) on Thursday August 09, 2007 @06:28AM (#20167523) Journal
    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.
  • by dargaud ( 518470 ) <[ten.duagradg] [ta] [2todhsals]> on Thursday August 09, 2007 @07:59AM (#20167925) Homepage
    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.
  • by Anonymous Brave Guy ( 457657 ) on Thursday August 09, 2007 @08:02AM (#20167935)

    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.

  • by stdarg ( 456557 ) on Thursday August 09, 2007 @11:18AM (#20170171)
    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. :)
  • by Crispy Critters ( 226798 ) on Thursday August 09, 2007 @03:26PM (#20173633)
    "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.

  • by renoX ( 11677 ) on Thursday August 09, 2007 @03:44PM (#20173849)
    [[ 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).

"May your future be limited only by your dreams." -- Christa McAuliffe

Working...