The most important feature of high-quality comments in code
By Tasos Papadopoulos
- 3 minutes read - 441 wordsIntroduction
As a software developer, one of the usually neglected aspects of writing code is commenting your code. Comments can help future developers - including yourself - better understand the code, make changes, and debug. Comments increase code maintainability, a trait you will apreciate more and more as you (and your codebase) mature.
A common misconception
Some developers believe that the primary goal of comments is to explain what the code is doing or clarify complex statements. I strongly disagree with this approach. Code is like jokes: if you have to explain it, it is bad. No comment can improve bad code. You will have to refactor your code and try to make it self-explained. This act alone will drastically improve code quality - and you will make your future self happy. Give yourself a pat on the back.
Documentation?
Others think that comments are part of the documentation. I believe this is based on the fact that code documentation should be within the codebase, and comments (such as JavaDoc) are a perfect place for it. While I totally agree with this idea - code documentation should be hand-in-hand with code, updated at the same time - I do have some concerns. For example, I can’t imagine onboarding a team member with:
- Welcome onboard Bob! Ready to tackle your first task? Just go ahead and read the comments in our 100k LOCs codebase. Good luck!
It would make more sense to provide a set of README files, a sequence diagram and/or perhaps a logical diagram of most important components.
Explain why you wrote the code
Comments can help explain why something was done or why a certain approach was taken. This is especially useful when working in teams or when coming back to a project after a long time. Comments can help reduce errors by providing additional context to the code. This can be especially helpful when debugging.
When writing comments, make sure to include the following information:
- Why the code is doing it this way
- Any assumptions you may have made (consider your comments as mini ADRs)
Additionally, make sure to keep comments up to date with any changes to the code. If you do only explain the why in your comments, you will soon find out that you will rarely need to update your comments. There are many reasons to refactor your code but a change in the why is less likely to occur.
Finally, it’s worth noting that comments alongside well-written tests can significanlty improve onboarding time for new team members, reduce time to troubleshoot bugs, and increase overall code quality.
Photo by Etienne Girardet on Unsplash