Font is Lavos HandyHave you ever noticed that almost every popular code highlighting scheme places comments in low-contrast grey-blue-on-white or dark-blue-on-black? Commenting has long been considered an important part of programming, yet in practice comments are written to be ignored. I think it is because they are typically added to satisfy bureaucratic requirements rather than to supplement the source code with information.
I used to be a huge supporter of comments. I loved to see glorious, rich, voluminous comments in all the code I read. I loved to write them. I thought that for a program to be 60% comments was a pretty good start. But as my teams began to write cleaner code, they sometimes would brag that the code was so clean that it
almost didn't need comments. Now I want all of my code to go beyond
almost.
I also have come to value vertical space in a file. I want it to be filled with working code instead of boilerplate and fluff. I hate scrolling through noise to find the code.
A few simple points to consider, and we can all have code that is more clear and gloriously free from noise and distraction.
- Comments provide information that is not expressible in code. Comments are meta-commentary. Anything that we can express in the code, we are duty-bound to express as code. Comments must never repeat the code, or the version control system. They are never substitutes for expressive code. Comments may express things like copyright, sources of algorithms, and reasons one algorithm or data structure is chosen over a more obvious alternative.
- Comments are to be deleted when they are obviated. Any comment that provides information available in the code must be deleted. We don't need comments to tell us that
x++ increments X. Any comment that does not provide value is to be deleted immediately. This applies to passages of code that are commented out. If the system runs fine without them, we don't need those lines.
- We should always strive to obviate comments. When we see a comment, we should take it as a challenge. If we can make the code express the content of the comment through refactorings (renames, extracting variables/methods/classes, inlining methods/variables, etc) then we should do so post-haste. If we can do it, then the code itself becomes smaller and simpler. And then the obviated comments can be deleted.
Inevitably someone will read this card as giving them license to stop writing comments, but that is a gross misunderstanding. If one takes a big steaming mound of poor code and removes the comments, it becomes an even more unmaintainable steaming pile of crummy code. There is a system and a balance that needs to be understood here.
This card doesn't tell us not to write comments, but rather to avoid writing code that needs them. Do I write comments? Yes, when I absolutely have to. But now I know when I have to.