On Beauty in Code

I was thinking about the topic of beautiful code this morning. There’s a lot of disagreement about what constitutes beauty in code. I’ve watched Marcel Molina Jr. talk about “Plato and Pythagoras”:molina. O’Reilly has published a “whole book on the subject”:oreilly. On the other hand, “Jeff Atwood thinks that there’s no such thing.”:atwood. I disagree with Jeff on this – I definitely think there is such a thing as beautiful code. But I’m not sure if my idea of what makes code beautiful is the same as others’.

What do I even mean when I say something is “beautiful”, anyway? Beauty is in the eye of the beholder, after all – there is no objective standard. For my purposes, I consider something beautiful when it triggers a certain emotional response. A flower is beautiful because I enjoy the simple act of observing it for its own sake.

!>/images/macbookpro.jpg!

When it comes to functional human-created objects, I’ve noticed that certain properties tend to trigger this emotional reaction. Here are a few products I find beautiful:

  • The “Mini Mag-Lite”:maglite
  • The “Fisher Bullet Pen”:fisher
  • “Chaco Sandals”:chaco
  • The “Apple MacBook Pro”:macbook

These are all products which are extroardinarily well engineered for their respective tasks. Out of that engineering emerges a kind of clean, austere beauty. I guess you could say my esthetic runs toward the “Bauhaus school”:bauhaus of thought.

!</images/fisherpen.jpg!

By contrast, a lot of the code I have seen held up as “beautiful” has more in common with “MC Escher”:escher or a “Zen garden”:zen. In the case of the former, the beauty is all about intricate, brain-twisting “cleverness”:camping. In the latter case, “divine purity of expression”:fibonacci takes precedence over more worldly concerns.

To me, beautiful code – code that I can enjoy reading for its own sake – has the quality of expressing its function simply and clearly. Like a Mag-Lite, its form reflects its function in a way that is elegant, straightforward, and easy to grasp.

!>/images/maglite.jpg!

One of the projects that has recently impressed me as having this property in its code is the “Ramaze”:ramaze web framework. The Ramaze “source code”:ramaze_source is clean, straightforward, well-commented (but not excessively so). Most methods are only a few lines long, and the lines themselves are short. White space is in abundance, setting off stanzas of code. And the logic itself is usually easy to follow.

Routing is traditionally a thorny area in web application frameworks. Here is the Ramaze routing code, in its entirety (minus some documentation):

#          Copyright (c) 2008 Michael Fellinger m.fellinger@gmail.com
# All files in this distribution are subject to the terms of the Ruby license.

module Ramaze

  class Route
    trait[:routes] ||= Dictionary.new

    class << self
      # Retrieve key from trait
      def [](key)
        trait[:routes][key]
      end

      # Set key to value in trait
      def []=(key, value)
        trait[:routes][key] = value
      end

      # remove all routes
      def clear
        trait[:routes].clear
      end

      # Resolve path according to routes.
      def resolve(path)
        trait[:routes].each do |key, val|
          if key.is_a?(Regexp)
            if md = path.match(key)
              return val % md.to_a[1..-1]
            end

          elsif val.respond_to?(:call)
            if new_path = val.call(path, Request.current)
              return new_path
            end

          elsif val.is_a?(String)
            return val if path == key

          else
            Log.error "Invalid route #{key} => #{val}"
          end
        end

        nil
      end
    end
  end

  # Shortcut for defining new routes.
  def self.Route(name, &block)
    Route[name] = block
  end
end

There is only one method of any length, @#resolve@. And that method has an easily recognizable cadence – if path matches some predicate, then perform some transformation, and return. Else move on to the next clearly-delineated stanza. This is another quality of beautiful code: each method body has a recognizable, almost archetypal “shape” which is not littered by special cases and digressions.

!</images/chaco-sandals.jpg!

If you enjoy reading code, I recommend taking a stroll through the Ramaze “source code”:ramaze_source. It is very nicely presented online in a custom source browser. And most of it demonstrates a similar clean elegance to the code above.

p{clear: left}. So that’s an example of what beautiful code means to me. What about you? What code do you consider beautiful?

[fisher]http://www.spacepen.com/Public/Products/BulletPen/Classics/index.cfm?productID=66
[maglite]http://www.maglite.com/product.asp?psc=2AAACELL&pt=R
[chaco]http://chacousa.com/Portal.aspx?CN=A9B61E6A03F0&MN=0E776DA03D8F
[macbook]http://www.apple.com/macbookpro/
[atwood]http://www.codinghorror.com/blog/archives/001062.html
[oreilly]http://www.oreilly.com/catalog/9780596510046/
[molina]http://rubyhoedown2007.confreaks.com/session09.html.
[bauhaus]http://en.wikipedia.org/wiki/Bauhaus
[escher]http://en.wikipedia.org/wiki/Image:Escher%27s_Relativity.jpg
[zen]http://en.wikipedia.org/wiki/Image:RyoanJi-Dry_garden.jpg
[fibonacci]http://haskell.org/haskellwiki/The_Fibonacci_sequence#Canonical_zipWith_implementation
[ramaze]http://ramaze.net/
[ramaze_source]http://source.ramaze.net/
[camping]http://redhanded.hobix.com/bits/campingAMicroframework.html

8 comments

  1. I’m not sure that I’m such a fan of the code to be honest. The fact that the if/ifelse cascade can’t be replaced with a case statement is a bit of a worry. Combine this with the use of is_a? and respond_to? and the fact that every consequence has its own nested if and it starts to smell of structural code.

    I realise that it’s going to increase the line count, but I’d prefer to introduce a few subclasses of Route (FilteredRoute, ProcRoute and StringRoute, say) and parcel the conditional logic out appropriately. Stick the key/value stuff in a make_route method, called from []= and the path munging into subclass#resolve methods and you start to have a collection of objects interacting with each other rather than a bunch of code messing with datastructures.

    It may not be a refactoring worth doing when there’s only three route types, but I would definitely be inclined to do it if the need arose for another kind of route.

  2. imho this implementation lacks a very important feature

    generating a url from a rule + some values,
    preferable based on the current “mount point” of the application

  3. imho this implementation lacks a very important feature

    generating a url from a rule + some values,
    preferable based on the current “mount point” of the application

  4. @PIERS and @RONNY the article isn't about the functionality, it's about effectively placing and using methods. Ramaze routing is regex based, not key based like Rails etc, that is why some of things you both are mentioning aren't there.

  5. @PIERS and @RONNY the article isn’t about the functionality, it’s about effectively placing and using methods. Ramaze routing is regex based, not key based like Rails etc, that is why some of things you both are mentioning aren’t there.

Leave a Reply

Your email address will not be published. Required fields are marked *