Why “clever” code is often really quite stupid

! Warning: this post hasn't been updated in over three years and so may contain out of date information.

To my mind, clever developers write clever code and that clever code is always:

  1. Easy to understand
  2. Effective
  3. Efficient

in that order. If you write code that isn’t easy to understand, then you aren’t being clever and nor is your code. I suggested this idea on StackOverflow in response to the “What is the most clever code you’ve ever seen?” question. It generated a lot of negative feedback from some folk, though the positive score (at the time of writing at least 😉 ) suggests more folk agree with me than disagree.

The fact that “clever” code often is anything but was highlighted by a recent article on The Daily WTF. It gives an example of a classic piece of “clever” code that not only resulted in an incomprehensible mess, but also ran far slower than could be achieved with a simple, easy to understand solution. In this case, the developer used the obscure C feature of long jumps, rather than a simple for or while loop.

So next time you are tempted to write a “clever” programming solution to some problem, ask yourself whether you are really being clever, or whether you are being a Homer Simpson.

3 thoughts on “Why “clever” code is often really quite stupid

  1. I’m inclined to disagree on your definition of clever code. Your example of the TDWTF entry doesn’t work – it’s not particularly clever, just an obsolete loop method that was, once upon a time, apparently more efficient than GOTO (and if you’ve ever used a do-while loop it’s not particularly “incomprehensible” either).

    As for readability – every single language implements comments for that exact purpose (there may be a few exceptions). If you have a clever implementation that isn’t immediately understandable, all you need to do is explain it to future readers through good commenting.

    Most problems just lend themselves to some thought. Implementing flags as single bits that can be OR’d, AND’d and XOR’d to form a set of flags stored as an integer is quite clever. The immediately obvious solution to that problem would be an array of bools, yet bitwise flags are common.

    Member functions that return pointers to their owner to allow for chaining are clever. And yet, the if you saw a function that returned its owner your first thought might be “WTF”.

    Clever coding is about not doing the obvious. It’s about ingenuity, about long hard thought and brilliant insights.

  2. I totally agree. Clever code resolves difficult problems in simple ways … while remaining intuitive

Comments are closed.