by mabbo · 4y ago · 0 comments
Write code that is obvious, clearly readable by future programmers maintaining the code. Don't do clever things that are hard to read and reason about until there is a strong motivating reason to do so.
Honestly most of the clever things you're about to do, the compiler is already going to do for you, but better and without the bugs you'll introduce when you do it wrong.
>Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it
Reminds me of a similar 'wordplay as argument' favourite quote by Terry Pratchett:
> You know how dumb the average person is? Well, statistically, half of them are even dumber than that.
(source: https://www.youtube.com/watch?v=zLkg-S_FfXc&t=3720s )
This is something I've come to realise more and more strongly as time's gone by. The code that I write isn't for me, it's for everyone coming after me. Including future-me. Gotta look after future-me.
I don't think this is actually the case, it's fairly easy to outsmart most compilers. A more honest argument is that it, in most cases, is a bad trade to make the code 3% faster by making it 10x more difficult to read.
Sometimes it is worth that effort, but that's the exception and you need to be able to motivate why it actually makes a difference. Show me a benchmark that demonstrates this is actually much faster (as a whole, not just the method), and then we can talk. "Clever" is in most cases another word for premature optimization.
There is nothing that will stop a code review quicker than "I discovered a clever way to..." A dozen engineers are going to have to try to reverse engineer your cleverness in order to safely make any change to your code, so you'd better make double-sure that the performance you're buying with your cleverness is worth the total maintenance cost going forward.
There are some times it's worth it (the Fast InvSqrt hack and many others), but most of the time, it's just tickling our intellectual curiosity for our own benefit, and that's a bad trade.
I agree, with the caveat that does not mean low-level/unabstracted/verbose code. Whilst each line of such code might be "obvious" on its own, the big-picture behaviour and inter-dependencies can be difficult to follow across multiple pages.
As an extreme example, machine code is completely "obvious" (e.g. "increment register RAX"), whilst being notoriously hard to follow (often requiring disassemblers, etc.)
Like, one thing that can be called a clever trick is to align the code vertically to make it easier to edit using vertical selections and macros in a text editor. That can actually make the code more readable and maintainable.
Honestly, I mostly mean things like "if we xor the two variables we can save one variable during the swap", etc. Clever code is not a great thing.