Write The Code You Wish You Had

One of my favorite software engineering mantras is, “Write the code you wish you had.” That sentence is a little bit cryptic at first glance, but once I grasped the meaning, it became a great way for me to get unstuck, especially when writing greenfield code.

The idea is that, when writing code, I frequently encounter situations in which I need a function that doesn’t yet exist. These situations can be paralyzing, because I want to continue writing the code I’m focused on right now, but I can’t keep going unless I write this new function. Writing the new function is a context switch that is mentally expensive and I want to avoid it. So I’m stuck.

The trick, and maybe this is obvious to you, even though it wasn’t to me, is that I can keep writing the code I’m focused on now. I can write down proceed with foo = some_function(arg1, arg2); even if I haven’t yet defined, or even declared, some_function(). I just write it down where I need it and keep going!

Of course, the code won’t compile or run, because I’m calling a function that doesn’t exist. But that’s okay, as long as I have some mechanism to ensure that I define the function later.

This works best with test-driven development, an approach whereby I define my automated tests before I write the functional code. That way, I always have a test that fails and reminds me to define the function I wish I had.

I picked up this mantra, “Write the code you wish you had,” through the Ruby on Rails ecosystem, which is fanatical about testing. I don’t remember who, precisely, first taught me the phrase.

But when I search for those words, one of the first results is this short episode of Developer Tea, by Jonathan Cutrell. He describes a similar mental shortcut, which is to think, “Wouldn’t it be nice if…?” He also suspects the phrase originates with Avdi Grimm of RubyTapas.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s