High-Quality Code

How do you define high-quality code?

Someone asked me this question recently. Without thinking too much about it, and under the pressure to reply before awkward silence kicks in, I answered the first things that came to my mind:

  • Code that is well tested, not strictly by having a lot of coverage but also by having readable and maintainable tests. Not by being tested once, but repeatably and automatically.
  • Code that follows the SOLID principles

I was alluding that I believe the characteristics of high-quality code are that it behaves as expected, is easy to read, maintain, extend. Sounds reasonable right?

Soon after the chat, I thought back on my answer and I realized I didn’t really answer the question, I only named some tools that help to produce high quality code.

I discovered my definition of high-quality code by asking myself: Why do I want to use these techniques and tools? Why do I want code to be easily readable and maintainable? Why do I want to break up our code into different levels of abstractions? Why do I want seperation of concerns, modularity, encapsulation? Why do I want code to be covered by automated tests? Why do I want const-correctness? Static analysis checks? Et cetera.

I had two answers:

  1. To prevent programmers from making mistakes.
  2. To allow programmers to easily and quickly modify the software.

Ah, but for the modification of software to be easy and quick, you need to eliminate the possibility of unwanted side-effects. So it really boils down to preventing any mistakes, the unwanted side-effects.

Being able to change software quickly is a qualifier that matters. You can prevent human error by preventing change, but the ability to change is a fundamental quality of code that allows programmer to specify software. If the purpose of code is to allow a programmer to specify software, then the ability to change makes it fit for purpose. And, the faster we can change code, the faster the resulting software can adapt to the needs of its users.

Therefore my definition is:

Code that minimizes opportunity for human error while optimizing for human productivity.