Code Virtues, part 4: Cleverness
August 29, 2007 – 7:44 amThis has been a conceptually difficult post to write, because unlike the other virtues we’ve explored, Cleverness is a bit … dangerous. Before we get started, then, a warning: don’t even attempt to be clever in your code unless it’s already correct, simple, comprehensible, and testable (or tested!)
So, cleverness. I think of clever code as that which, while it may not be transparent at first glance, produces that ‘A-ha!’ flash of insight as you look at it. Clever code teaches you something, and you’re a better developer for having learned it. Blocks and procs in Ruby are clever - newbies often don’t grasp how powerful they are, but once they figure it out, the sky’s the limit.
Cleverness is, of course, observer-dependent (what’s clever to _why may be incomprehensible to me), and as a result your code can be too clever, when it flies over the heads of the people who have to read and use it. This, then, is the double-edged virtue, and is easily the most difficult to intentionally obtain.
The good news, however, is that you generally don’t (or shouldn’t, at least) try to write clever code - unlike the other virtues (and like beauty, I’d argue), cleverness is something that just happens every now and then in your code. When you struggle over some part of your code, only to replace it after suddenly realizing a simple solution was hiding behind the problem the whole time - that’s when you get clever code. Trying to be clever, however, generally just pushes you into the too-clever range, and your code is the worse for it.

