Building Beautiful Apps from Ugly Code

I wish I could entirely blame my computer science degree for undermining my sense of aesthetics, but I can't. Much of it was self-inflicted from being too immersed in programming and technology for its own sake, and it took me a long time to recover.

There's a tremendous emphasis on elegance and beauty in highbrow coding circles. A sort implemented in three lines of Haskell. A startlingly readable controller for a washing machine in half a dozen lines of Forth. Any example from Structure and Interpretation of Computer Programs. It's difficult to read books, follow blogs, take classes, and not start developing an eye for elegant code.

All those examples of beauty and elegance tend to be small. The smallness--the conciseness--is much of the elegance. If you've ever implemented a sorting algorithm in C, then you likely had three lines of code just to swap values. Three lines for the entire sort is beautifully concise.

Except that beauty rarely scales.

Pick any program outside of the homework range, any program of 200+ lines, and it's not going to meet a standard of elegance. There are special cases and hacks and convoluted spots where the code might be okay except that the spec calls for things which are at odds with writing code that crackles with craftsmanship. There are global variable updates and too many parameters are passed around. Bulky functions because things can't be reduced to one or two clean possibilities. Lines of code wasted translating between types. Odd-looking flag tests needed to fix reported bugs.

Small, elegant building blocks are used to construct imperfect, even ugly, programs. And yet those imperfect, ugly programs may actually be beautiful applications.

The implications of that are worth thinking about. Functional programming zealots insist upon the complete avoidance of destructive updates, yet there's a curious lack of concrete examples of programs which meet that standard of purity. Even if there were, the purely functional style does not any in way translate to the result being a stunningly powerful and easy to use application. There's no cause and effect. And if there is a stunningly powerful and easy to use application, does that mean the code that runs the whole thing is a paragon of beauty? Of course not.

The only sane solution is to focus on the end application first. Get the user to experience the beauty of it and be happy. Don't compromise that because, behind the scenes, the code to draw ovals is more elegant than the code to draw rounded rectangles.

(If you liked this, you might enjoy Write Code Like You Just Learned How to Program.)

permalink September 8, 2011

previously