How to Write Reliable Code
I've learned the most important key to making reliable software, a method that has served me well for over 20 years.
Follow this simple rule:
Write a comment for each line of code, making it a complete sentence to express a complete thought.
You should aim to write for two computers in parallel -- one is the CPU, and the other is between your ears.
Why does this technique work to make software more reliable?
Line-by-line comments serve as a kind of logical checksum for the code, such that if the code and its comment differ in function, then you know immediately that work needs to be done in that area. Often, a coding bug will be revealed as you are writing the comment that goes along with the code.
More broadly, line-by-line comments serve to hold the intellectual context and keep your mind connected to reality.
2 comments
[ 3.0 ms ] story [ 17.3 ms ] threadSecondly, a major problem with line-by-line documentation is that you will soon end up in a situation where the documentation does not agree with the code. A bug was fixed, but the comment wasn't updated or vice versa.
Additionally, what makes for good comments in complex systems is not "what" a specific line of code does. Good programmers can read the code they are paid to write in. A good comment identifies "why". Why is this code necessary, why is it being solved in this specific way, why should I, as a developer of this system, care about this code.
Line by line comments can be hard to read. It helps to use clear naming, nouns for things, verbs for actions, spelling stuff out in full. I prefer block comments which only explain what isn't obvious in the code and what could not be expressed more clearly in the code.
As for comments not agreeing with the code, that should get picked up during peer review. Of course, the best comprehension test is when you come across the code a year later to make some change.