Should your code be readable or clever?
Sometimes it’s not about who’s right or who’s wrong, but more about the best approach to achieve the goal. How you define success depends on what you and your team values.
In coding, there are many ways to achieve the same outcome. Some approaches are good, while others are better. For example, one can implement a clever solution with minimal lines changed, whereas another can have many lines changed but is more understandable.
Personally, I find readable code to be more valuable that clever code. This is because we humans spend more time reading code than writing it. As a result, focusing on readability allows for easier maintenance, better improvements, and less bugs and regression. Enhancing the mental models of the code is a boon for developers.
Once upon a time, I wrote some clever code at my job. I was pretty damn proud of how clever it was and I even showed it off to my coworkers. I didn’t touch the code for 6 months and when I came back to it, I had no idea what it was doing. Ironically, I asked myself, “Who wrote this shitty code?” and was embarrassed to find out that it was me after doing a git blame. I learned a very important lesson — that although code is executed by machines, it’s written by humans. From that day on, I spent more time writing readable and well-documented code.
But you may quip, “Won’t you be sacrificing optimization?” Most of the time, lines saved and optimization aren’t worth the sacrifice in readability — especially if it’s premature. Based on the 80/20 rule or the Pareto principle, there are other places in your codebase that can give you higher gains than prematurely optimizing some parts of your code. Benchmark to discover where they are and optimize where necessary.