Code CAN Be Beautiful

In his review of Code Is Beautiful, Jeff Atwood decides that no, actually it isn’t. He’s fairly adamant about it too:

Ideas are beautiful. Algorithms are beautiful. Well executed ideas and algorithms are even more beautiful. But the code itself is not beautiful. The beauty of code lies in the architecture, the ideas, the grander algorithms and strategies that code represents.

I just can’t agree with this. It’s effectively saying that a representation cannot be beautiful; only the underlying thing that’s being represented can be beautiful. Worse, this argument is extended to literature and art as well, and quotes a reader review from Amazon that quotes a little Russian poetry and rhetorically asks whether any non-Russian-speaking reader can see beauty in it.

This drives me nuts, it really does. Of course the representation can be beautiful, and it can also be ugly. And the beauty of the representation can have an amplifying effect on the subject of the representation. Form and content are related. A non-Russian-speaker may not appreciate Russian poetry, but that doesn’t mean that form itself has no value - it means that, in this case at least, the value of form is dependent on the content. If you don’t understand the content, you don’t appreciate the form.

This isn’t an absolute, though. In literature, there are many techniques for adding value to form. Alliteration, assonance, metre, and many more techniques are all structural techniques for beautifying form. I’d argue that pretty much anyone can appreciate the compact and succinct beauty of the phrase veni, vidi, vici without understanding what it means (”I came, I saw, I conquered”).

There are countless other examples. You don’t need to understand Italian to enjoy opera, for instance. In fact, I’ve even heard it argued that understanding the content of an opera can diminish the experience, since the actual meaning is often fairly bland and distracts from the simple appreciation of the complex sounds and interplay of the language in the hands (or lungs) of a world-class performer.

So what’s the equivalent in software? I think expressiveness and elegance are key. In particular, code that is able to express ideas without adding a lot of noise. I’m very partial to Haskell for this sort of thing - for instance the canonical quicksort implementation is wonderfully precise:

quicksort []        = []
quicksort (x:xs)    = quicksort less ++ [x] ++ quicksort greater
    where less      = [ y | y <- xs, y < x ]
          greater   = [ y | y <- xs, y >= x ]

If you know the quicksort algorithm, then the 2nd line of code there is about as precise an expression of the underlying concept as you could hope for. If you write the same algorithm in C or Visual Basic, I believe that you can objectively distinguish the ‘beauty’ of these representations of the same underlying concept. This is only possible if the representations do indeed have the quality of beauty.

Another, perhaps even better, example is the naive-recursive Fibonacci generator in the same language, which is remarkably close to the mathematical definition:

(from literateprograms.org)

fib n
    | n == 0    = 0
    | n == 1    = 1
    | n > 1     = fib(n-1) + fib(n-2)

Note I haven’t read the actual book under review here, and I have no reason to doubt the assertions that the book doesn’t deliver. I do, however, take umbrage at the statement that code (or language) cannot be beautiful.

Related Posts:
digg    del.icio.us    reddit    stumbleupon

25 Responses to “Code CAN Be Beautiful”

  1. gwenhwyfaer Says:

    “If you know the quicksort algorithm, then the 2nd line of code there is about as precise an expression of the underlying concept as you could hope for.”

    Unfortunately, handing it a pre-sorted list will demonstrate the gulf between beauty and practicality.

    In any case, since Haskell’s data structures are immutable, mergesort is a much better match for it; the only advantage of qsort is that it can execute in-place - which…

  2. Brantley Says:

    No, it really just depends on the font. :)

  3. Jonathan Ville Says:

    Firstly, if you think code is beautiful, then:

    qsort [] = []
    qsort (x:xs) = qsort (filter (= x) xs)

    is a far more elegant implementation of quicksort, which essentially does the same things as your list comprehensions, but in a more succinct way (list comprehensions are implemented using filter and map anyway).

    Secondly, the reason this is ‘beautiful’ has nothing to do with the elegant syntax and much more to do with the fundamental ideas behind functional programming, and the maths used to show that the lower assymptotic bound of the running time is n log n (which is analysis of algorithms - a beautiful subject). And of course, there’s always the fantastic proofs by induction you can do in functional programming.

    And I bet you can’t write a functional program that finds fibonacci numbers much faster using matrix multiplication (and diagonalisation of matrices to make this fast). The maths behind that is truly beautiful.

    There is good syntax and bad syntax, but at the end of the day syntax is transient and a bad way to judge a language.

  4. she Says:

    “A non-Russian-speaker may not appreciate Russian poetry, but that doesn’t mean that form itself has no value - it means that, in this case at least, the value of form is dependent on the content.”

    That is true, but of course one also has to understand the language in question. And when one does, even speaks and writes multiple questions, there are two points:
    - how easy is the given language (write, speak, think)
    - how beautiful is it

    An algorithm will ultimately stay the same, but it does matter how it will look in different languages. And there we are at languages which are just plain ugly.

    By the way, algorithm’s are in itself quite beautiful but let’s look at reallife examples of code at work, like a somewhat-complicated task that is done by code. To me, languages such as C or Java simply have less appeal than say python.

  5. Aaron Says:

    Unfortunately, that’s _not_ quicksort, but an out-of-order lazily evaluated mergesort equivalent. Quicksort is in-place.

  6. russ Says:

    >Firstly, if you think code is beautiful, then:
    >
    >qsort [] = []
    >qsort (x:xs) = qsort (filter (= x) xs)
    >
    >is a far more elegant implementation of quicksort, which
    >essentially does the same things as your list comprehensions,
    >but in a more succinct way (list comprehensions are implemented
    >using filter and map anyway).

    Actually, I prefer the one I posted. Probably a subjective thing, but I find mine maps more directly onto how I conceptualise the algorithm in my head. But hey, as so many people have already said, beauty is in the eye of the beholder, right? Also, I agree with you that syntax is a bad way to judge a language, but that’s not really what I’m trying to do here. Haskell’s qualities as a language don’t really influence my perception of certain Haskell snippets as ‘beautiful’.

  7. russ Says:

    >Unfortunately, handing it a pre-sorted list will demonstrate
    >the gulf between beauty and practicality.

    Yes indeed, but isn’t that the case in so many other disciplines? I don’t write emails to my boss in iambic pentameter, after all.

  8. Alan Says:

    >Firstly, if you think code is beautiful, then:
    >
    >qsort [] = []
    >qsort (x:xs) = qsort (filter (= x) xs)
    >
    >is a far more elegant implementation of quicksort, which essentially does the >same things as your list comprehensions, but in a more succinct way (list >comprehensions are implemented using filter and map anyway).

    I don’t see how this will return anything except an empty list. Is there something missing?

  9. Weave Jester Says:

    > qsort [] = []
    > qsort (x:xs) = qsort (filter (= x) xs)
    >
    > is a far more elegant implementation of quicksort

    The comment system ate everything between the less-than and greater-than operators. Hopefully this will come out right:

    qsort [] = []
    qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

  10. Georgi Y. Dimitrov Says:

    How beautiful is the code is important, because it makes the difference between programming languages. If the code is beautiful, it is readable and maintainable and vice versa. Lisp and Smalltalk have many virtues but ugly looking code and are unsuccessful and always will be. C, C++ and Perl have a bit less, but still ugly code and their popularity goes down. Java, C#, Ruby and Python have more beautiful code and their popularity is on the increase.

  11. yaxu Says:

    Well said, of course representation can be beautiful!

    It’s a chain of representation — e.g. some code represents an algorithm, which in turn represents the tenets of some mathematical model, which in turn represents some aspect of the physical world. Each step can be beautiful and/or ugly.

    It’s not as if a piece of code was ever a perfect representation of an algorithm. There are always interesting details of implementation which may have profound aesthetic effects on the results.

  12. Jonathan Ville Says:

    > Unfortunately, that’s _not_ quicksort, but an out-of-order lazily evaluated
    > mergesort equivalent. Quicksort is in-place.

    This is actually correct, and I think quite important to note. The function should be re-named ‘msort’.

    However, merge sort has an average and worse case time complexity of O(n log n). Quicksort has a lower bound of O(n log n) and upper bound of O(n^2), but in practice is very fast, if you have a randomized, fat pivot, and an un-sorted list.

  13. beza1e1 Says:

    Mergesort is more stable than Quicksort, though. This is why GHC now uses Mergesort for List.sort and dropped it’s old Quicksort.

    Neither of them looks beautiful in the real world by the way.

  14. Pete Says:

    You must see the point about the Russian poetry though. I agree that code can be beautiful, but not knowing anything about Haskel, I found your examples to be ugly and mostly unreadable (even the second, which I wouldn’t have connected to the maths without the diagram right above it).

  15. anonymous Says:

    > Unfortunately, that’s _not_ quicksort, but an out-of-order lazily evaluated
    > mergesort equivalent. Quicksort is in-place.

    Quicksort: divide is interesting, conquer is trivial.
    Mergesort: divide is trivial, conquer is interesting.

    In other words, the algorithm presented in the post is not mergesort or an equivalent of it. It’s entirely fine to call it quicksort even though it’s not in-place.

  16. russ Says:

    >You must see the point about the Russian poetry though.

    I do indeed see the point about the Russian poetry - I didn’t see much that was beautiful about it either. I just believe that this isn’t always the case. Some representations may lack beauty, but it doesn’t follow that ALL representations lack beauty. The point of this post was simply to refute that statement by providing counterexamples.

  17. Daily Links - February 24, 2008 | Alvin Ashcraft's Daily Geek Bits Says:

    […] Code CAN Be Beautiful (Russ Gray) […]

  18. Programming expert Says:

    1) Quicksort (and mergsort) have nothing to do with being “in-place” or not. There are in-place versions of both (though in place merge sort is usually called heap sort) and…. functional-friendly versions of both. :)

    2) Understanding is very much bound with beuty. When I used to read Smalltalk code I thought it was awful because I didn’t understand it (the same problem Georgi has above). After I learned the syntax and saw the elegance of what it was doing it quickly became the most beutiful language I have ever seen. Lisp is high on that list as well, based on it’s simplicity and elegance.

    Things we don’t understand we tend to see as *ugly*. Especially when the thing in question is from a domain we expect to understand.

    You point about Italian opera misses the mark because for many who enjoy opera they content is the sounds and visuals. We understand very well what sites and sounds are pleasing to us (though we probably wont know why). Probably a similar percentage of people watch opera for the plot as do for a porno.

  19. rahul Says:

    I am partial to c++ in this case,
    See the inplace quicksort in c++ compared to haskell’s not-inplace one.
    taken from: http://erikhaugen.blogspot.com/

    template
    void quicksort(Iter begin, Iter end) {
    if(begin == end) return;
    Iter pivot = stable_partition(begin, end, _1 < *begin);
    quicksort(begin, pivot);
    quicksort(pivot + 1, end);
    }

  20. anonymous Says:

    > I am partial to c++ in this case,
    > See the inplace quicksort in c++ compared to haskell’s not-inplace one.
    > taken from: http://erikhaugen.blogspot.com/

    Nice all right. I’m not too sure about the entirely in-place bit though. When I looked up stable_partition to see what it did, it seems that most implementation partition through allocating a temporary buffer…

  21. Michael Trick’s Operations Research Blog » P.G. Wodehouse approach to Modeling? Says:

    […] Unfortunately, not, but close. Refactoring in this context is “any change to a computer program’s code that improves its readability or simplifies its structure without changing its results”, according to wikipedia. So when a computer program is built on over the years, at some point there is a wish to rewrite or otherwise consolidate the code so it is back looking new, ideally with the effects of all the changes intact. Of course, this is relevant to OR also. We often put together models that have been added on to, changed, and modified to within an inch of their lives. And at some point we would like to have the model “we should have written” in the first place. So there is a temptation to toss everything out and start again. In fact, I often recommend doing so in my classes. But that isn’t very good practice, according to contemporary work in refactorization: Now, the first mistake to avoid here is the compulsion to throw it away and rewrite from scratch. So often when confronted with a vast seething moiling spiritless mass of code a developer throws his hands into the air and declares it a lost cause. How seductive is the thought that 31,000 lines of code could be thrown away and replaced with ~15,000 lines of clean, well-designed, beautiful code? […]

  22. Thomas Says:

    Not only can code be beautiful, but programming itself should be counted among the ‘fine arts’. Or so argued Pierre Lévy in his 1992 book De la programmation considérée comme un des beaux arts (On computer programming as a fine art):
    http://www.amazon.fr/dp/2707121541/

  23. -jn- Says:

    Ah, how we programmers LOVE to refuse to separate our concerns! ;-)

    All the quibbling about programming language preferences and “I can write that function in fewer characters” puts me in mind of the book Strictly Speaking by Edwin Newman. Written in the immediately-post-Watergate era, the book is a wonderful extended lament on the difference between elegant ideas expressed in homely fashion (with examples from Yogi Berra, Casey Stengel, etc. IIRC) vs empty ideas expressed in flowery language (most of the politicians and advertisers of the day).

    I’d also recommend The Crystal Goblet by Beatrice Warde for the same principles applied to typography. (See http://gmunch.home.pipeline.com/typo-L/misc/clar.htm for discussion.)

  24. vFiles Says:

    -regards to all

    ,what is important is that your code flows smoothly and it is according to your algorithm and most especially you can predict wether you can maximize its capability and upgrade its limitation. Thats how beautiful your work is, your programme!

    ,other than that, can someone analyze the program that i developed it is a sorting algorithm. I made this program not to surpass the quicksort but since im in the process i used to attempt surpassing the fastest quicksort. Now i already finished it and based from the demonstrations and observation it is many times faster than the quicksort. I still want somebody who really knows how to evaluate so that i am confident that my algorithm was beautiful.

    , thanks

  25. Max Says:

    This blog is simply smashing. In my humble opinion of course. As this post is rather debatable I don’t think all your blog visitors are going to agree with it.

Leave a Reply