Beautiful Code
Yeah, this post is inspired by the O’Reilly book of the same name. It’s a few years old, but it’s a good one. When I first read the title of the book, I thought it was about beautiful looking code. It’s not… necessarily, but I found something peculiar when reading it. Code that implements a beautiful design usually ends up looking, well, beautiful.
I find in large designs the most beautiful lead up to a bang. Say there is a class that has a handful of functions. If you trace into any particular function it might do very little and then hand off to another function. The other function might do just a little more and then hand off to a function that terminates the stacking elegantly completing the task. These classes usually take careful planning and down right experience to design.
Then there is simple logic that doesn’t need careful design. There are many ways to do the same thing, but to me some just look better than others. I don’t know how to explain it. Maybe other coders have experienced what I’m talking about. I’ll call it Feng Shui of coding. I’ll give an example. I like
food = "tacos";
if (vegetarian)
{
food = "tofu tacos";
}
but I don’t like
if (vegetarian)
{
food = "tofu tacos";
}
else
{
food = "tacos";
}
I have more subtle preferences too. I put spaces after my if, for, and while statements before the parenthesis. I also space between my operators. I think it just looks right.
Take a look at a source file of lua. Now take a look at a source file from SDL. They are written in the same language, but they are so different. Lua likes squished short functions. SDL likes spaced out phrases in fewer functions. The casing is also drastically different.
I find this interesting. It might invoke a giant who the hell cares from others, but then again I’m a source code junkie. I rather enjoy in my leisure browsing the code of say Android or even the Linux kernel. I always think a coder’s style says a lot about how they even solve problems. It’s interesting to see what ‘greats’ prefer. Which brings us back to the book Beautiful Code. That’s what it is all about. You get to look at what some of the great problem solvers have to offer.
I have thought for a while that source code can be art. I’m serious here. There are many elements that come into play. There is the overall style (curls at the end or on the next line). There’s spacing and casing. There’s the verbose license headers and the “Fred made this” headers. There is the witty one line comment. There is the part that I find the most intriguing–why it was written. Is it an MP3 decoder that is legally gray in binary form (unlicensed that is)? Is it a reverse engineered structure of a media streaming protocol Apple was keeping proprietary? Is it a home brew implementation of Microsoft’s .NET Framework for another operating system than Windows? I find that the most beautiful.







Leave your response!