Code quality can be measured in four levels:
- (Working code)
- Reliable code (minimum)
- Readable code (ok for short-lived code)
- Changeable code (standard level)
The code quality of a project directly impacts its maintainability.
Generally you should aim for level 3. If the code will stay for less than a few months, it may stay at level 2. Never go below level 1.
0. Working code
You have implemented that feature and it works. Congrats! You have reached level zero, which means three levels of code quality lie ahead.
First, make sure your code is reliable:
1. Reliable code
In order to reach the baseline for good code, make your code:
- deterministic
- tested (automated)
- scaling with data
Other people will be able to rely on your code, and it will not fail them.
However, you should not stop here. Any piece of code is usually read may times, so please make it readable:
2. Readable code
Your code is here to stay. Expect it to be read many times in the next years. Your future self and other people will thank you if they can easily make sense of it. This makes it easier to debug in case of errors, and to extend in case of feature requests.
If your code is more than a single script file (i.e. some project or larger application), you'll need to make its entirety readable.
Follow these guidelines to keep your code readable and understandable:
-
Have a project README as an introduction
-
Choose descriptive names. Everything should have a name that says just what it is.
However, sometimes the What is not enough to make sense of the code. This is where code comments come into play: -
Group belonging lines with empty lines ("code paragraphs")
New code is usually bright and clear to the developer who just wrote it. To check its readability, a good strategy is to return after a few months. You will have forgotten the direct context, but will still be able to recall how everything was meant. Take some time to fix anything that is not easy to grasp.
Also see https://www.joshwcomeau.com/career/clever-code-considered-harmful Show archive.org snapshot .
Readable code is a noble thing, but there is a king class:
3. Changeable code
In most projects, code is not only read, but also changed. Most programming paradigms and patterns lift your code to this level. While it is the hardest level to reach, it pays out in the long term. Many wise people have thought about rules that help reaching this level: