⬅ back to the index

Good Code

There are two rules for good code:

  1. Minimize the cognitive burden of running the code in one's head from start to finish, exactly, correctly, and without guessing.
  2. Your intent should be perfectly unambiguous.
You may expand this to...

There are four rules for good code:

  1. Less code takes less energy to read and understand as long as it's not overtly confusing.
  2. Don't make people look somewhere else to understand what something means or will do, within the limits of rule 1, because every value you need to remember and every visual jump increases the cost to maintain mental execution state.
  3. Avoid code that will happily do something unexpected if someone accidentally hits a key without realizing it.
  4. Use structural elements to clarify what the code is supposed to be doing so that it's easier to detect when it's accidentally not doing that.

Extended Edition

Draining code:

Debugging code requires running it in your head. Running code in your head costs mental energy.
Needing to remember and keep track of things increases the mental burden.
This is exponentially worse for everyone who isn't the author.
So make the read as linear and compact as possible to reduce the burden you place on others. [1]
[1] - within the limits imposed by interface enforcement mechanisms available in the language

Dangerous code:

Code that just keeps running but does the wrong thing if someone accidentally deletes a character or presses tab will start silently doing the wrong thing because someone will accidentally delete a character or press tab, and you won't know until it's too late.