DEV Community

Cover image for A short comment on comments in the code

A short comment on comments in the code

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.

A stop sign with sign below informing “This is a stop sign"
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;
}
Enter fullscreen mode Exit fullscreen mode

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!

Latest comments (43)

Collapse
 
ibi123 profile image
Ibee Bhai
Collapse
 
stanciudragosioan profile image
StanciuDragosIoan

I disagree with the fact that comments are bad. I tend to favour comments as they are extremely helpful (even if they might seem redundant).

I worked many times in legacy code bases with 0 documentation and 0 comments. I wasted many many days trying to figure out code logic (just to much later understand that in fact the logic was only half of the problem and the other half was lying in business logic - comments would have definitely helped there).

For the reduntant comments, I think they will be good for any new joiner on the project (they might be redundant to you the one who wrote the code but not to some1 completely new).

Yeah you can have descriptive names and yeah code is self explanatory (if the functions/blocks have a decent length and you don t have like 400 + lines functions) but the why behind it is critical in understanding everything.

For my projects I make it as a rule in PR to have comments changed if you edit the function underneath otherwise PR won't pass.

Collapse
 
awps profile image
Andrei Surdu

Learn to ignore comments and read them when you don't understand the code. It's just so simple.

Collapse
 
ddaypunk profile image
Andy Delso

Very well written Dominika and thank you for the tldr pointing to common sense and writing better code overall!

Collapse
 
arnebab profile image
Arne Babenhauserheide

Code speaks to the machine and humans, comments only speak to humans. That’s why comments can always be easier to understand and give more context than code.

They may not always do that, and if the code gives the information sufficiently easy to take in as the comment, I prefer just having the code, but I spent the last years working on a codebase of which a part suffered from having no comments due to adhering strictly to clean code.

The parts with comments are always easier to understand.

Leaving out comments leads to code that replicates the comments but does not actually make a difference.

The main differences between the name of your function and a comment is that you have more constraints in spelling the function and that the function shows up in code-completion and at any place your function is used (which can be an advantage, but also adds more constraints).

Collapse
 
alidarrudi profile image
ali

It was an interesting article. I rarely use comments

Collapse
 
brense profile image
Rense Bakker

Very well written and explained! 👍

Collapse
 
jaffparker profile image
Jaff Parker • Edited

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.

Collapse
 
crisclacerda profile image
Cristiano Lacerda • Edited

I think you missed the main point of when comment are useful and what good comments are all about, explaining intent and purpose. Why things were done that way. No matter how clean or good your code are, these are never going to be readable from the code.

Collapse
 
tosey profile image
Tosin Seyi • Edited

Bro, let me be honest with you, I disagree with your points to some extent until someone answers the following:

First, you said comment makes your code longer and can be misleading. I don't see how it can be misleading if you're doing the proper thing in your code, but it helps a lot.

You add comments to your code knowing that it will help you and other developers a lot in the future so that you can remember what you did and what you were thinking then. Therefore, this should not bother you even if it makes your code longer.

This alone goes a long way in helping to enable you make updates to the code that will not break your project at all.

Now, there is one thing that majority of developers are not thinking 🤔 about. And the thing is, even if you use meaningful names instead, what if a function is doing one task before, let's say you created a function called "uploadExcelFile()" and after some weeks or months, you come back and add another task to the function, how do you update the name of the function to reflect its current behavior after you have used the name in so many files? Do you change the name.of the function to reflect the current update and also change the name in every file as well or you leave it like that when commenting is not an option? But if you leave the name of the function as it were before you updated the code, then the name will still be showing that the function has not been updated when in fact, it has been updated (because you cannot know the future name you will give a function until you write a code for it).

Would it not be better to also add extra comment on top of the function to explain the current update than changing the name of the function in every file that you have used it? Can someone answer that one? I guess you guys aren't thinking towards that direction 😂

I have heard someone talk like this on Quora before, and I'm sure you must have used some of the points from there too.

Collapse
 
arnebab profile image
Arne Babenhauserheide

We use the rename-command to change the name automatically everywhere it is used.

Collapse
 
tosey profile image
Tosin Seyi

Yes for you. But some developers don't do that. They just leave the first name like that. What of in a case where the editor you use doesn't have the rename command? Can you do that conveniently with notepad++, vscode, atom, sublime text, etc?

Thread Thread
 
arnebab profile image
Arne Babenhauserheide

You asked, whether it would not be better to add a comment. No, it would not. The function name is the information that shows up in code completion and is the first thing people see. If you can, you should make sure that it reflects what the function does.

You might still be forced by your tooling to add a comment instead, but that’s then a question of tooling not of what’s the right thing to do.

Also you may want to add a comment anyway, because the three-to-five words you use in a function name are often not capable of capturing the more subtle information you need when using the function. Look at the Javadoc of some of the Java Collections methods.

You could make the name much longer, but then it is polluting the code where it is being used with information you only needed when writing the code, but usually not while reading it, because there you can usually assume that the original author made the right choice.

(Sidenote: your argument would be much stronger, if you asked what to do for public API of libraries. There it is impossible to change the name of the function where it is used, because you don’t control those parts of the code).

Thread Thread
 
tosey profile image
Tosin Seyi

Read my comment very well. It seems you don't understand it. Plus, you're even contradicting yourself bro 🤔 .

Thread Thread
 
arnebab profile image
Arne Babenhauserheide

No, I’m not contradicting myself. I’m telling you that you make a weaker argument than you could.

In my first message I answer your general claim (what would you rather do? If I can, I’ll refactor; depending on the IDE that can be as simple as a single keyboard shorcut). In my second answer I add the limitations and fine details that must be checked to take a good decision.

Don’t expect a simple yes/no answer when it comes to comments.

Also I’m not your bro.

Thread Thread
 
tosey profile image
Tosin Seyi • Edited

And my reply then was "Is it everybody that uses IDEs?" Most developers I Know use vscode and do they keep replacing the function name in every file they used them when they add new features to it? This is my main point. You can speak for yourself but don't try to speak for everybody. Because you can't.

And also, it's your choice whether you are a bro or not.

I won't reply you again. Because it seems you are proving obstinate.

Thread Thread
 
amabe_dev profile image
amabe_dev

I agree with @arnebab

And my reply then was "Is it everybody that uses IDEs?" Most developers I Know use vscode

VSCode has the features required to rename the function. Even vim has it if well configured.

If people choose to code with a dumb editor, they are not using adequate tooling to make good software.

And if you choose not to use the features of the editor then I can't argue that you will have to find hacks like generic function names and comments. But that code will not be as clean as it can.

Thread Thread
 
arnebab profile image
Arne Babenhauserheide • Edited

I answered you “You might still be forced by your tooling to add a comment instead, but that’s then a question of tooling not of what’s the right thing to do.”

That’s for the ones without working rename tooling.

Collapse
 
kuya1284 profile image
kuya1284 • Edited

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.

Collapse
 
ddaypunk profile image
Andy Delso

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.

Collapse
 
kuya1284 profile image
kuya1284

Was there something about my comment you were disagreeing with? I agree with what you're saying.

Collapse
 
bbutlerfrog profile image
Ben Butler

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!

Collapse
 
abh1navv profile image
Abhinav Pandey

I'm not in favor of comments which do not get generated into docs but I don't agree with rigid opinions like this one. We cannot control the need of comments but should reduce them as much as possible by maintaining good readability.

Collapse
 
drstrangelooker profile image
Dr. Strangelove

This is the correct take.

Collapse
 
ecyrbe profile image
ecyrbe

If you are writing a reusable library, you should definitely add documentation comments.
These kind of comments are there to explain how to use your library and allow Doc tools to generate the user documentation.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.