Are you writing useless comments in your code?
Knowing when and what to comment makes a difference.
Quality code usually consists of good comments that help us understand the code better. But what are good comments? When should you comment the code? What makes a code comment a great comment?
Hopefully, in this short post, we will answer all the above questions and more.
The purpose of commenting is to help the reader know as much as the writer did.
At the time of writing the code, you have a lot of information in your head. When other people read your code or even you a few months later, that information is lost — all you are left with is the code you’ve written.
In this post, we will go over what to write down, what not to write down and how to pack as much information as possible in a short comment.
We will take a look at the following things:
- What not to comment
- What to comment
- Put yourself in the reader's shoes
What not to comment
When other people read our code, a comment takes away time and attention from the actual code. That said the comment should provide valuable information to the reader otherwise the time spent reading the comment was worthless. So what is the difference between valuable and worthless comment?
Let’s see an example of worthless comments in the code:
// User class definition
class User {
// Constructor
constructor() {}
// Get user's first name
getFirstName() {
return this.firstName;
} // Set user's age
setAge(age) {
this.age = age
}
}
All these comments are worthless because they don't provide any additional value or information to the reader.
Don’t comment on facts that can be derived quickly from the code itself.
Don’t comment just for the sake of commenting
This should be self-explanatory. Don’t comment your code just because you are used to putting comments on every line. Other developers should understand your intentions just by going through the actual code.
Don’t comment bad names
This one is a bit trickier. From time to time everyone names their variable or function with a bad name, but a comment shouldn't be the fix for a bad naming — fix the name instead.
Let’s look at a simple example:
// Replace encoded characthers in a string
function cleanString(string) { ... }
This is a simple example with a short comment, but when dealing with something way more complex you can imagine how long it would take for someone to explain what the code does. All this could be avoided if the function was better named. Since we know that all it does is to replace encoded characters in the given string, a more self-documented name could be decodeString
.
What to comment
Now that you know what not to comment, let’s take a look at what you should be commenting but often doesn't. A lot of good comments can come out by simply writing down a few words from your thought process when developing a piece of code. As mentioned at the beginning, you have a lot of additional information about the problem you are solving, and if this information doesn't get written it’s lost forever.
Write down your thought process
The comment could be something as simple as your observations while developing the code.
Here is a simple example:
// This function shouldn't have await since we don't need the result.
This comment teaches the reader we shouldn't wait for the execution of this code. When dealing with a code that has await
on every function call this might be helpful to document since it might be mistaken for a bug.
Here is another example:
// This call might timeout. That's OK since the data will be resent in the next invocation.
Without the comment, the reader might think there is a bug in the code and waste time trying to reproduce the bug and to fixing it.
A comment can also contain ideas for improvements or code redesign:
// This class is getting too big. Maybe we should create a new subclass.
Comment the flaws
Finding the flaw or the bug in the code is sometimes more time consuming than fixing it. That's why it’s crucial for every developer to comment on the flaws they make or find in the codebase. When you know something could be improved don't be afraid to put a comment. It’s highly likely that someone else reading the code was having the same issue and knows how to fix it.
There a number of popular markers to mark the code:
- TODO — stuff that needs to be done
- HACK — mark the piece of code that is customised for a specific use case
- FIXME — known issue
- NOTE — be aware of …
Your codebase might have specific conventions for when to use which marks. Most of the time you will see the TODO
since is versatile and most well known.
The important thing is that you should always comment on your thoughts about how code works, what could be improved, what is missing and what could potentially go wrong. It will help you and your team in the long run.
Comment your constants
When defining a constant there is usually a background for what the constant does or why it has that specific value. For example, you might see a constant like this:
const NUM_OF_WORKERS = 8
At first glance, you might think this constant does not need a comment. But why is the value for this particular constant set to eight? The person working on this code definitely has the answer — why not embed it into the code in the first place. The code could look something like this:
// Set to 8 since we encounter some problems with concurrency when // working with more workers
const NUM_OF_WORKERS = 8
Now the person reading the code has insight on how the value was adjusted and set to this specific value.
Sometimes the value of the constant is not important at all. Commenting this could be still useful since the person reading the code immediately knows that the constant could be changed without causing any harm.
// Set to 100 since is a reasonable limit - noone will buy more that // 100 items anyway. Still could be changed in the future
const MAX_CART_SIZE = 100
There are also some constants that don’t need comments. For example SECONDS_IN_AN_HOUR
— the name is clear enough.
Use common sense when deciding when to comment on your constants. Is the name clear enough or does it need an additional explanation?
Put yourself in the reader’s shoes
When deciding what to comment imagine what your code looks like to an outsider. Is the code clear, is the problem the code is solving clear, is the solution clear, etc. This technique will not only help the readers to understand your code but also make you a better programmer. You will subconsciously think about the clarity of your code and therefore write better code.
Anticipating likely questions
When someone else reads your code, there are parts that are likely to make them think — What? Why? Your job is to put a comment at those parts and answers there question in advanced.
For example:
function clearArray(array) {
array.length = 0
}
Why is this code setting length of the array to zero? Why not instead just set the array to an empty array like this: array = []
In JavaScript, the upper statement creates a new empty array. If you have a reference to the variable array
anywhere in the code, the value will remain unchanged. On the other hand when you set the length of the array to zero, even if there are references to the array in your code, values will be changed.
Big picture
One of the bigger challenges for the new team members is to understand the big picture — how data flows through the system, where the entry points are, what is the expected output, etc. The person who designed the system often skips these comments.
When designing the system ask yourself: if a new team member joins your team and sits next to you, what question will he/she be asking. Another great exercise to find out what are the unclear parts is to explain the codebase to your teammate — were there any questions? You should probably put a comment on those parts.
The key when documenting the big picture in your code is to keep your comments short. A few well-chosen sentences should be enough to explain what the code is doing. These comments should only be a guide to the person reading the code, formal in-depth documentation should be written separately.
Summary
The purpose of a comment is to help the reader know what the writer of the code knew at the time of writing the code. Comments should be short but useful. They should give the reader insights about the code and answer any confusion — what the code does and why.
Writing good comments is not easy. Most of the programmers usually don't like to write comments, but with enough practice, you will find adding a comment is not that hard and time-consuming. Also once you get the grasp of value those short comments provide, commenting the code will become a no brainer to you.
What not to comment:
- Facts
- Fixes for bad names
What to comment
- Insights about the code
- Flaws and knows bugs
- Behind the scenes of the constants
Keep in mind
- What parts of the code are unclear
- Surprising behaviour
- Big picture
If you have any comments or additional tips, please leave them in the comment section!
You should also read my previous post on how to better name your functions and variables here: