Writing good code: how to reduce the cognitive load of your code.

Low bug count, good performance, easy modification. Good code is high-impact and is perhaps the main reason for the existence of the proverbial 10x developer. And yet, despite its importance, it eludes new developers. The literature on the subject usually amounts to disconnected collections of tips. How can a new developer just memorize all that stuff? “Code Complete“, the greatest exponent in this matter, is 960 pages long!

I believe it’s possible to construct a simple mental framework that can be used with any language or library and which will lead to good quality code by default. There are five main concepts I will talk about here. Keep them in mind and writing good code should be a breeze.

Update: Mia Li was kind enough to offer a Chinese translation of this post here.

Keep your personal quirks out of it

You read some article which blows your mind with new tricks. Now you are going to write clever code and all your peers will be impressed.

The problem is that people just want to fix their bugs and move on. Your clever trick is often nothing more than a distraction. As I talked about in “Applying neuroscience to software development“, when people have to digest your piece of code, their “mental stack” fills up and it is hard to make progress.

Don’t personalize your work in ways that would require explanations.

Don’t code “your way”. Just follow the coding standards. This stuff is already figured out. Make your code predictable and easy to read by coding the way people expect.

Divide and conquer it

Complex code can often be clarified through modularization, and there are more ways to do this than just creating more functions. Storing the result of long conditionals into a variable or two is a great way to modularize without the overhead of a function call. This will even allow you to compose them into larger conditionals, or to reuse the result somewhere else.

The approach when breaking a problem down should be to have each section as focused as possible, affecting only local state, without mixing in irrelevant issues, and without side-effects if at all possible.Programming languages and libraries often come with their issues, and abstracting them away can help your code mind its own business. The Single Responsibility Principle is another example of how focused and localized code leads to good design.