I’ve been writing code for well over 30 years now.
In 30 years of coding, I learned my code has to make sense to me long after I’ve written it. Later on, I started working on code shared with others. My code had to make sense to them, too.
When code got really complicated, I used to add a comment to explain it. I thought that would solve the problem. It didn’t.
Comments rot. We update the code, and forget to update the comments. Sometimes, the change happens far from the comment but still affects its correctness.
Quite often, comments imply our code would not be clear without them. This, in turn, means when I try to understand the code where it is used I am likely to have to navigate to its definition to read the comment.
Other comments are just the result of habit and add no value. Worse, some comments just add to the confusion.
I have learned to avoid comments almost entirely. It took me years to understand what self-documenting code meant, but I get it now.
Be explicit. Name your constants, variables, functions and classes based on what they do. Make sure the name is accurate. Avoid abbreviations.
If a line isn’t clear – refractor it. Extract a meaningful variable. Extract a well-named function. Move it to a well-named class.
With this insight, looking at my earlier attempts at clear code… Well, I have no comment.
(You can read about this idea in depth in Uncle Bob’s Clean Code)
I may get commissions for purchases made through links in this post.