The Prettiest Code

This afternoon I started to wonder…

I’ve been a programmer now for 20+ years, but what is the best piece of code I’ve written in all these years?

The first thing that popped in my mind was this. It is a piece of code that can very quickly, in near linear time, generate de Bruijn sequences. I ‘invented’ it after reading a scientific paper that described how to quickly generate ‘Lyndon words’. I knew with Lyndon words you could easily generate the de Bruijn sequences. So I implemented it and adopted it for de Bruijn. Read more about this here.

Why is this my favourite piece of code? Well, it is small, compact and does something impressive. I couldn’t find a lot of implementations that had the fast runtime my code had. And it wasn’t trivial to implement, I had to do quite a lot of research and it felt like I myself did a little inventing. I probably wasn’t the first to write the algorithm though, but it felt like that for a while.

But is it…?

As a programmer I write code every day. And what I do even more is read code. If I have to guess, for each line I write I’ve read about ten times more. And after more than two decades of programming, I’ve seen my share of source code. This taught me something important. Is the piece of code I mentioned the best code I’ve written? I don’t think so.

What I thought the best code should have:

  • Looks smart
  • Amazes people
  • Jumps out
  • ‘I could have never created that!’
  • It is magical!

The code I picked sure had some of these properties. But is it really the prettiest code I’ve written? No..

When you are working in a large codebase the best (and prettiest) code has the following properties:

  • Doesn’t stand out
  • Looks trivial
  • You don’t notice it’s there
  • You hardly ever need to change it
  • ‘Gah, anyone could have written this’

The best code is code you don’t notice, code that doesn’t stand out, code that looks like anyone could have written it. It doesn’t contain smart things, it looks mundane. This is something we should always strive for… simple code.

So what is the best piece of code I’ve ever written? It is the code that will never be git-blamed, nobody will ask questions about it and nobody will even notice it exists.