Write Stupid Code
This post has been translated to Chinese.
In the last couple of months I developed a certain approach to writing code. Whenever I write a new function, class or method I ask myself: “Is this code stupid enough?” If it’s not, it’s not done and I try to make it stupid.
Now, stupid code does not mean “code that doesn’t work”. Stupid code should work exactly like it’s supposed to, but in the most simple, straightforward, “stupid” way possible.
Anyone could write it and anyone reading it should be able to understand it. It shouldn’t make the reader think about the code itself, but about the problem at hand. It shouldn’t be long, it shouldn’t be complex and, most importantly, it shouldn’t try to be clever. It should get the job done and nothing more.
What does stupid code look like? It depends on the problem it’s trying to solve. Take meta-programming, for example, which is often considered complex and “black magic”. Does asking myself “is this code stupid enough?” mean “no meta-programming allowed”? Not necessarily, no. There are certain cases, in which the problem can be solved in the simplest way through meta-programming. But there are a lot more cases in which meta-programming is unnecessary and additional baggage on top of the solution, which gets in the way of understanding what the code is supposed to do.
The goal is to get rid of the baggage, to chip away at it until the most stupid, still working, tests-passing code emerges.
Keep in mind the “stupid” here: “it works” is not good enough. A lot of complex, “look at this clever trick”, overly-abstracted, unreadable code works and makes the tests pass. That’s not what I’m after. It has to be stupid: not clever, not complex, not hard to understand.
Besides “stupid” the resulting code might also be described as “elegant”, “clean” and “simple”. But the “write stupid code” mantra is not as elusive as “write elegant code”, for example, and seems far more achievable, which makes the approach much more valuable to me. And besides that: I find it much more likely to start out with “write stupid code” and end up with an elegant solution than the other way around.
Not every elegant solution is straightforward, but “stupid” ones are, per definition, and can also be elegant.