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!

Oldest comments (43)

Collapse
 
amabe_dev profile image
amabe_dev • Edited

First of all, before writing a comment thing if you can provide the same content in the code.

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.

Collapse
 
domizajac profile image
Dominika Zając (she/her) 🇵🇱

It's a good tip - thanks for that!

Collapse
 
drstrangelooker profile image
Dr. Strangelove

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.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀
// Comments that add value are parsable 
// they are not just read by us. but by a
// computer, an example would be jsdoc
// Javadoc and other inspired systems
// finally some comments allow
// introspection and full type definition for
// languages without such luxury.
// Comments in code an also be Terrible
Enter fullscreen mode Exit fullscreen mode
Collapse
 
azlan_syed profile image
Azlan-Syed

comments seem to be an idiot code for the computer

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀
// I don't understand unless it's a comment
Enter fullscreen mode Exit fullscreen mode
Collapse
 
paulknulst profile image
Paul Knulst • Edited

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!

Collapse
 
mylopeda profile image
Jakob Carlsson

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.

Collapse
 
ddaypunk profile image
Andy Delso

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.

Thread Thread
 
paulknulst profile image
Paul Knulst

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:

  • the comment says this method uses bubble sort to sort the array
  • now someone goes to the function that actually sorts the array and updates it to use quick sort algorithm
  • he changes the sort comments
  • because the method still does the same - sorting an input array - the underlying code can be changed.
  • outer functions that uses the sort function have documentation that maybe says: calls an sort function that uses bubble sort.
  • this leads to wrong documentation if the person who changes one function only change the comments above the changed function and not in EVERY function that uses the function

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.

Collapse
 
drstrangelooker profile image
Dr. Strangelove

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.

Collapse
 
paulknulst profile image
Paul Knulst

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

Collapse
 
frankfont profile image
Frank Font

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.

Collapse
 
baenencalin profile image
Calin Baenen

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!

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.

Collapse
 
imcheesecake profile image
Freddie • Edited

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.

Collapse
 
mylopeda profile image
Jakob Carlsson

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.

Collapse
 
camco profile image
Camco

If you are writing comments that confuse. It's not the comment, it's the writer.

Collapse
 
star-codex profile image
Erin

Comments help me understand what's happening at a glance as I'm working, especially with new things I'm trying out to keep me focused on what it's supposed to do. It's also a form of rubberducking for me if I get stuck for a minute. I will add stuff above functions for clarity but that's about it. They get stripped after I'm familiar enough with what I'm doing to explain it to myself and others without missing a beat.

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.

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
 
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
 
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
 
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
 
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
 
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.

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