Code is poetry

Matt Mullenweg gave the WordPress project the tagline “code is poetry” and I’ve always liked it.  I don’t take it literally, though I know some people have had a go at doing just that.

But for me its a great principle when you’re coding anything – if you find yourself writing code that does lots of horrible specific things, with lots of extra lines to cope with certain situations, something is probably going wrong.

And I’ve just hit another example now.  JavaScript to disable one form field when you tick a checkbox, and re-enable it when you untick said checkbox.

Now, you might logically write code to the effect of “if the checkbox is ticked disable the field, or if the checkbox is not ticked enable the field” then link that to the checkbox’s onlick event.  That would work.

But there’s a more elegant – dare I say it, poetic – solution.

When the checkbox is clicked on, simply invert the state of the field.  The code (HTML & Javascript) for this becomes:

<input type="checkbox" onclick="document.myForm.myField.disabled=!document.myForm.myField.disabled" />

The ! (not) in this case doing in the inverting (since “not true” is false, and “not false” is true).

Instinctively you know you’ve got the best answer because there’s a symmetry, even a beauty, about the way that works.

A simple example, but a great principle.

So yes, for me, code is (or can be) poetry.

Leave a comment