Clear is better than clever.
Another life lesson from Go Proverbs
This proverb doesn’t just apply to programming; it applies to any creative act.
Clarity is a gift I give to others right now.
And it’s a gift I give to my future self.
One thing that can get in the way of being clear is being too clever. Whether this is writing a blog post, a song, a piece of code, or your last will and testament, it pays to be clear.
In the context of coding, clever code might be a dense one-liner full of clever mechanisms of the language that keep the logic compact. Here is a clever example of a “one-liner” function that can find the value of the nth position of the Fibonacci sequence in Python:
fib = lambda n: n if n<=1 else fib(n-1) + fib(n-2)
A clearer solution expands this and makes your work easier to understand and maintain by others.
if n <= 1:
return fib(n - 1) + fib(n - 2)
Being clever can feel amazing. This is especially true when you are in a flow state. Expressing an idea with a dense but correct structure can feel like magic. You are firing on all cylinders. You are in the zone. You get what you are doing, and you are knocking things out. But can others follow what you are expressing? Six months from now, can you follow what you are expressing? And what about documentation and performance? Neither of the functions above correctly handles negative values for n, and the function is not performant for larger numbers. In my clever solution, that one-liner is not maintainable, but I can expand it for maintainability in my clear example.
Here, I’ve added:
Type hinting in the function signature.
A proper docstring with an explanation of how the function behaves.
The ability to properly handle positive and negative values for n.
A significant performance optimization with the
functools.cachedecorator to provide memoization
Optimizing for clarity is an iterative process. I’ll often start with something too clever and rework it until it is clear.
As I’ve stated earlier, this holds for any creative act. We can optimize for all sorts of things that we design and build things. We can optimize for cost, availability, efficiency, speed, and performance. We can optimize for clout, bragging rights, and referencing the past. No matter what we optimize for, before sharing our work with others, we should strive to clarify our intent.
This is my second post expounding on my favorite Go Proverbs. You can read my first post here.
Notable Links of the week
These are links to things I found online this week in this section.
I stumbled upon this story about John Carmack’s case for inlining code.
This fascinating post discusses mixing audio and image-compressing tools to create interesting results.
It’s fascinating to me that this guy is one of the wealthiest people in the world.
Steve Mould’s video on a “clever” perpetual motion device is fun.