My short comment on why you should stop using comments in your code (unless in special cases)
Tl;dr
Please, think twice before adding comments to your code. Probably, there are no needed and will just confuse people who will read your code later on. Write a clean, readable code instead. Thanks in advance!
Intro
I was thinking about this article for a very long time. As I often help young developers I see how many of them love adding comments to their code. And I still remember lecturers from my studies who tried to convince us that the good code should be commented to be readable for other developers. However, the last straw that breaks the camel’s back was the tweet you can see below.
Source: Programmers Memes Twitter
This photo is the best comment on adding comments to the code ever. I wish I could say it’s an exaggeration. But what is the difference between the above and the comment in the function below?
// function to count the perimeter of the triangle
// input: 3 numbers, output: number
const countTrianglePertimeter = (a: number, b: number, c: number)
: number => {
return a + b + c;
}
Unfortunately, we can still find a lot of snippets like that in the code. And I strongly encourage you to avoid them! Why? There are many reasons to stop adding useless comments to your code.
Reasons to stop adding comments to your code
Comments are just redundant to the code
Very often comments do not provide any additional information to the user. They describe exactly the same things as the code does. So why duplicate the info for the reader? Use meaningful names instead. Extract logic to separate functions if needed. Extract const values to the well-named const variables. Simplify code e.g. using fast returning and avoiding multiple nesting if needed. Well-written code is even easier to read by non-native English speakers than long descriptions in plain language!
Comments are often out-to-date
The code in live projects changes. There are always some bug fixes or new functionalities which require not only adding the code but also editing the existing source. And as long as code is always up-to-date, hardly anyone remembers about updating the comments. So, comments are often out-to-date and present the old logic of the code. Remember, comments can lie — the code never does!
Comments can be misleading
Programmers very often want to keep comments short and write them after writing the code. Because of that, the text can contain some mental shortcuts and simplifications. What is hidden between the words may be obvious to the author, but not to the reader. Using the wrong word may make the whole meaning completely different. And when you make a mistake in the code — tests will catch it. Unfortunately, there is no automated way to test if your comment is not misleading. So just skip it — as long as it’s possible.
Comments make the source code longer
It’s quite obvious — each comment’s line makes your code file longer. And our brains don’t like long walls of text. Opening a file with many comments makes it difficult to find really important lines and see all the code on the screen. When you can’t see all functions on one screen it’s easier to make mistakes or create some inconsistency. Also, computers have to handle it, so it may have an impact on performance. For many years, fans of the minimalist approach to life have been saying that fewer things mean less chaos. And I agree with them — at least when it comes to programming.
Everyone is afraid of removing or uncommenting commented code
Sometimes we leave the code commented in case it will be useful in the future. But let’s be honest — there are no more scary things than code that is commented on and no one knows why. Can we just remove it? Why it’s not working? What happens if we uncomment it? Leaving unfinished or “almost working” snippets commented in the code could be useful many years ago. But now we have great code versioning systems like git — removing the code with meaningful and descriptive commit message (and eventually adding a tag to make it easier to find later on) is much more convenient, clear, and easy to revert. Also, almost no one starts the implementation of a new feature by looking for some commented code in the codebase. So chances that someone will use your currently unnecessary code are really low.
Special cases when comments can be useful
In the previous section, I described many reasons for removing comments from your code. However, there are some special cases where comments can be useful — even in the production code! They are described below — but remember: I don’t call them special cases by accident :)
Regexes
There is an old saying “If you have a problem and use regex to solve it then you have two problems”. Regular expressions are great and useful but unfortunately not very readable. It’s why adding comments explaining what a given regex is checking is not the worst idea.
Specific business logic
Sometimes business requirements are tricky and not intuitive. Theoretically, the logic should be covered in some tech documentation but let’s be honest — no one likes reading tons of docs when need to fix one small thing. It’s why adding a short comment explaining the reasons behind some not obvious decisions may be OK. Just check if it’s a confusing logic that cannot be well explained in the code.
TODO comments
The developing process is split into steps. And it’s OK to not include all changes in one commit but leave them for the following ones. When your project is small and you don’t use any tool to track tasks (like Jira or Github Issues), having TODO comments saying what should be changed and where can be useful. Especially because code editors have special mechanisms to support them. The problem here is that this solution is not scaling and can be inefficient for big projects.
Tips on comments and avoiding them
Some tips may help you decide if comments are needed or how to use them correctly. First of all, before writing a comment thing if you can provide the same content in the code. Why do you need free text to express your intention? Why code cannot speak itself? Very often the need of writing a comment is just a symptom of a refactoring need. Also, if you have to write a comment (because of one of the reasons described in the previous section), keep a comment as close to the code which it describes as possible. If you add your thoughts at the beginning of the file, a person reading the code probably won’t notice it or not update it while implementing some changes. And talking about changes — don’t track them in the source code. Git is definitely a better place to track changes and their authors. Also, git (or any other versioning system) is your friend if you want to remove some functionality but have a chance to revert it. Don’t comment on the source code — create a commit with a meaningful name instead and programmers will find it in history if needed. Thanks to all of those tips your code will be cleaner, up-to-date, and more readable for everyone.
Summary
Of course, there are no strict rules about adding comments to the code. Each case is a little different and your role as a developer is to determine if comments can be useful in your case or distract/mislead the person who will read your code. I encourage you to think twice before you will add a new comment to your code and consider their props and cons. Remember: comments can lie — code never does!
Top comments (43)
One question that I find useful to know if a comment should be added or not is: Is it at the same level of abstraction as the code?
If it is at an higher level of abstraction, it provides context and might be useful. If it is at a lower level of abstraction, it provides constraints and might be useful. Both help explain a technical decision. And this the purpose of comments, to explain the why. That avoids making others loose their time figuring out a decision or trying something that we found inappropriate.
If it is at the same level of abstraction, it should not be added. It says the same thing the code says. And if it is needed to understand the code, I agree with you that it is a sign that refactoring is needed.
But thinking in level of abstractions might not be easy to grasp. Especially for beginners to whom those kind of tips might be useful.
It's a good tip - thanks for that!
Another tidbit that is useful in a comment is documenting special values in the inputs or outputs. No one wants to trace code to find out what are valid parameters or what meaning a nil or null takes in a parameter. Depending on your language the expected types can be critical as well.
Sometimes this is obvious, but if it isn't a comment is much easier.
comments seem to be an idiot code for the computer
After reading A Philosophy of Software Design (amazon.com/Philosophy-Software-Des...) my take on this is that comments that describe WHAT the code is doing on the same abstraction level as the code should not be written. If the comment is describing WHAT the code is doing on a higher abstraction level it might be something good to write, might be, it depends on the situation and how the comment is written (so that it really is on a higher abstraction level).
Comments that describe WHY the code is doing something or doing something in a specific way should be written when needed (and also sometimes when not needed) to tell the other developers (and future you) why a specific way was chosen. A good example from my personal work life is when I wrote a function with about 20 lines of code doing a thing that could be done using a one-liner with a regular expression, the reason for me to chose the 20 line method was that it was much much quicker and this specific method would be running many times so how quick it was running was more important than if if could be written using fewer lines of code or not.
What about doc-comments, for example in Rust with
///
?Those are used to generate documentation later on and IDEs like VSCode use it to give you helpful descriptions when hovering over types.
Adam Crockett (whose name I swear I've seen before) makes a good example of this in their comment.
This. I never use comments for functions because the name should be a good enough description.
However, I almost ALWAYS put comments over my properties because I HATE not knowing what the property is used for when I have to use another teams stuff. And also it helps when you get the intellisense bubble... and also with Storybook.
I have a good advice for every developer.
If possible turn color of your comments to red so that you see them as an error and then try to delete them as fast as possible.
If you still think comments are useful, read this book amzn.to/3B3yUB8
And if you do not want to read the book, see this presentation by the author: https://www.youtube.com/watch?v=7EmboKQH8lM&t=1s
Also, Uncle Bob explains in the book (and in the presentation) how clean, readable and maintainable code can be produced.
To be honest, everybody should read this book!
I would say that if you read Clean Code then you should also read A Philosophy of Software Design (amazon.com/Philosophy-Software-Des...) to get another view on the matter. Just because Uncle Bob wrote something in Clean Code doesn't make it the only way to see things. There are some problematic things with the Clean Code view that makes code harder to read.
I’ve read Clean code and I’m pretty sure he’ he didn’t say comments are bad. He provided cases in his experience where they were and were not useful.
No he did not say that in his book.
But within his presentation (the YouTube link) he explains how he personally does it with his IDE just to avoid having comments all over the place.
The main problem with comments is that they will not be updated after changing some lines of codes. Or maybe a function has a comment how this function solves a problem by using XY. But if XY gets changed maybe the comment for XY will be updated but the calling functions will not receive an comment update.
as an example lets think about you have a function that uses another function to sort an array:
This is just an very easy, understandable problem that should describe the problem with having comments everywhere. You can easily exchange the sorting algorithms and the call hierarchy with other things, but the comment-problem still exist.
This is dumb advice if taken literally. 99% of code comments may be useless. But the comment that says "this seems like it should be done more easily with this other feature, but bug-NNN forced us to do this" can save a lot of work in the future.
Honestly, these comments that say please refactor are the worst.
Please avoid them in a team. Use your Repository Tool (Bitbucket, GitHub, Gitlab, etc) to add a comment within the tool and add an issue/ticket as soon as possible to fix the bug.
Using comments instead of refactoring/fixing the code is one of the worst things to do.
It will lead to unreadable, not maintainable code. Because if you do it once, you will do it everywhere. And instead of having clean readable code you will have old, wrong, buggy, not-optimized functions within the whole codebase. And then you fix one bug and will create multiple others because you did not read the comments... ALL comments because you never know where a lazy developer has done such a thing...
Please, don't do that.
Never... Really... Never
One case where lots of comments are welcome is working on legacy code that nobody on the job wrote and nobody fully understands. When you figure out some complicated interaction --- please by all means leave a big fat warning comment. Nobody will complain about it.
The premise of this article is the same as what I read in Clean Code (by Robert Martin). Basically, don't state the obvious and write self-documenting code instead. Thank you for reminding developers how to write cleaner code.
As I previously stated he didn’t flat out say to not comment, just not to make obvious comments. Doc blocks and complex code is still okay to document.
Was there something about my comment you were disagreeing with? I agree with what you're saying.
Totally agree! Variable and function names should be descriptive in and of themselves. I even wrote a post about it some time ago lol
I'd add one more case in which comments are allowed, it's kinda similar to the business logic - hacks lol. When you break your head over a problem and end up using a hack to go around it, it's useful to know if the hack is redundant or still needed.
It should include links to your research too, to be able to pick it up when you (or a colleague) has more time.
If you do not use docblocks, you are not writing code that meets standards for the majority of modern languages and it should not be accepted in any project. Please ignore this advice if you are learning to develop and use docblocks and follow other important standards!
If you are writing comments that confuse. It's not the comment, it's the writer.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.