Writing software you can still read next year
Most code is read far more often than it is written, usually by someone who has forgotten writing it. That someone is normally you.
I have a rule for the code I write: I should be able to come back in a year, with no memory of writing it, and work out what it does and why.
That rule has changed more of my habits than any style guide.
Clever is a cost
The clever solution is enjoyable to write and expensive to read. Every abstraction, every indirection, every trick that saves four lines is a small tax charged to whoever reads the file next.
Sometimes that tax is worth paying. Usually it is not, and it is paid dozens of times to save a few minutes once.
I would rather read three obvious functions than one elegant one.
What actually helps
Almost none of it is about formatting:
- Name things after what they mean in the domain, not after what they are technically. `pendingRefunds` beats `filteredArray`.
- Put the reason in a comment, never the mechanism. The code already says what it does. Only a person can say why it had to.
- Keep the shape of a function honest. If it fetches, transforms and writes, it should look like three things, not one.
- Leave the failure cases visible. Code that hides its edge cases reads beautifully and behaves badly.
Comments as a record of decisions
The comments I am glad to find are never explaining syntax. They are the ones that say: this looks wrong but the upstream API returns dates in two formats, or we tried the obvious approach and it broke under load.
That is information that exists nowhere else. Once the person who knew it leaves, it is gone, and someone will spend a fortnight rediscovering it.
The real test
The test is not whether a reviewer approves it. It is whether a competent stranger can change it safely without asking anyone.
If they can, the code is finished. If they cannot, it is still a draft, however well it works.