Thinking about Clever Code
The trick I covered in my previous post got me reflecting on "clever" code. Most developers I know (myself included) have learned to mistrust clever code - we see it and the intuition we've developed provokes a gut reaction of "oh no, how can this blow up in my face?"
Speaking personally, however, this trick doesn't make me feel that way - I find it quite elegant! Which makes me wonder if there are actually two types of clever code, kind of like how Rich Hickey makes the distinction between "simple" and "easy" in his talk "Simple Made Easy". Code is simple when it is uncomplicated and has few moving parts; easy code, on the other hand, is code that is familiar to the reader.
So let's say there are two types of "clever" code: we'll use "elegant" to refer to code like the glibc trick, and "sly" for the other kind. I'm not exactly sure what sets the two apart - it's one of those famous "I'll know it when I see it" things - but here are the criteria I've come up with so far:
- Sly code feels like you're getting away with something - it provokes a reaction of "wait... that works?!"
- Elegant code, however, provokes a reaction of "I don't know if I would've thought of that, but it feels almost obvious in retrospect". The most extreme examples visit upon the reader an almost-fundamental shift in how they use a language feature or view a problem - "can't unsee", but in a good way.
- You can figure out what elegant code does without needing to run it.
- Elegant code tends to get crystallized into language idioms.
- An elegant code solution in language A may not be elegant in language B: the glibc macro argument trick would be wholly unnecessary in other languages.
I intend to keep an eye out for other examples of this, and potentially update this post as I come across them. Maybe it's time I dusted off that copy of "Beautiful Code" I've put off reading for the longest time to help me find some!
Published on 2024-08-09