How Should I Go About Commenting My Code?

Timothy Quirk
6 min readJan 2, 2019

--

The proper use of comments is to compensate for the failure to express yourself in code.”

Robert Cecil Martin, Clean Code: A Handbook of Agile Software Craftsmanship

It seems that everyone has a differing opinion on how to use comments when coding. Opinions that range from — any need for a comment is a failure to write readable code — to any comment is better than no comment at all.

With such a wide range of strong opinions, how am I to decide which approach is right for me? For those who are unsure, and looking to establish a strong foundation from the get-go, comments are used by developers to write notes to themselves, as well as to those who will read their code in the future.

That is to say that comments are notes to be read by developers. That statement alone is of significant importance! Compilers execute the written code regardless of what comments are left for those who review the code.

Which means comments should be written for humans. I want to emphasize the importance of this, so I believe it bears repeating. Comments should be written for humans.

The Purpose of Comments

Truly effective comments should never describe what is happening. Any competent developer should be able to determine that from the code itself. But comments can provide insight to future-you, or members of your team, on the ‘why’ of how you wrote your code.

When you are coding, you are looking to solve a problem. You know what the problem is and you are working towards a solution. Step by step, you inch towards your goal, and with some testing, you can be assured that your program works. However, in the future your program may need to scale to accommodate more users or additional functionality, and when you review your code in weeks, months, or a year’s time you are unlikely to remember the ins and outs of how each method works together to achieve that goal.

Additionally, you aren’t likely to be the only one who is going to read your code. But even if you are, you will doing future-you a favor by leaving comments that provide insight into your thought process while you were developing the program.

As a general rule of thumb, take some time to pause and reflect before writing. Ask yourself what is most confusing about the program and how can you best explain it in “dummy” language? Also consider why you’re writing the code exactly as you are.

Jake Rocheleau, “Source Code Comment Styling: Tips and Best Practices

Photo by Mathew Schwartz on Unsplash

But don’t take too long to think it over, like our skeleton friend here. You want your code comments to be high-level overviews: insightful, but not in-depth pieces of investigative journalism.

Highlights for useful comments:

So what should I be pulling away from this overview, you might ask? This list is by no means comprehensive, but highlights what I believe are the most important elements that you want to keep in mind when commenting your code:

  1. Comments should provide insight into the why of how you went about solving the problems before you.
  2. You should write comments knowing that humans will read them, and thus knowing that they need to be understandable.
  3. Comments are not books; you should not need long drawn out paragraphs describing step by step what is happening. Rather, you should have quick, clean notes that will further the reader’s understanding of the inner workings of your program.

That’s all well and good, but if you are like me, having an example or two to review may be far more useful than a numbered list to look over.

What not to do (examples written in Ruby):

Example 1:#here I loop through all stored trades
def my_stocks
trades = Trade.all.select {|trade| trade.investor_id == self.id}
not_sold = trades.select {|trade| trade.bought_sold == "bought"}
end
Example 2:#determine if trade has already been completed
def transaction_already_completed?
if self.status != "pending"
false
else
true
end
end

Example one is a poor use of a comment because it simply repeats what the code is doing, which is already evident from the code itself. The context of why is what is missing. The comment is also written in the first person (“I loop…”), which isn’t relevant to the context of what the program is doing either. Before reading on, how might you tweak example one in order to improve the utility of the comment?

Now take a look at example two. It is slightly more useful in that the manner it is written is more relevant to the program itself. However, yet again it just tells you what the code is doing. In fact, the comment repeats the method name. Why did this method need to be written? It may be an important step in process, but there is no context to what that process may be. Again, see if you can think of a way you might tweak the existing comment to improve it?

Potential tweaks for improvement:

Example 1 (revised):#selects all of an individual user's current stocksdef my_stocks
trades = Trade.all.select {|trade| trade.investor_id == self.id}
not_sold = trades.select {|trade| trade.bought_sold == "bought"}
end
Example 2 (revised):# called during a stock purchase/sale to assure that each
# transaction occurs only once.
def transaction_already_completed?
if self.status != "pending"
false
else
true
end
end

What did we do differently in example one? It is still not perfect, but it does provide more insight into the utility of the function, since we do not have the entire program in front of us to review. However, with this comment we know that there is an important distinction between stocks that have been bought and sold, and that we only want to return stocks from a given user that they own.

Example two is an even stronger revision. This revision provides the context that this method is flexible enough to be used in both stock purchases and sales. Which means we now have a good idea where to look for this piece of code in our program. That would be very useful hint if any issues arose when this program was going through QA and another engineer needed to dive deeper into our code.

Additionally, revisions one and two are both very readable, concise, and to the point: all significant elements of making a strong code comment. With time, you will be able to isolate these items and comment your code with ease. Your team may also have expectations of exactly how your code should be structured and commented. Those expectations will help guide your comments and will be useful to you and those who read your code in the future.

Remember: you are the one writing the original code and you are the best situated to know how and why it works. Be sure to document the ‘why’ of it all and you will be much happier with yourself if you ever find the need to revisit that project again.

With that in mind, my final suggestion is for you to ask yourself when you’re reading other people’s code: what context am I missing when I read code that I did not write? Thinking of comments from that perspective may help you gain further insight into writing comments for your own code down the line.

Photo by NESA by Makers on Unsplash

While I haven’t solved the debate on whether comments should be used at all, now you can see the utility in a well-written comment. I hope that each of you will strive to write comments that provide context and answer the question of ‘why’ for when coding yourselves. Future-you will thank you!

--

--

Timothy Quirk

Full stack web developer based in NYC with a passion for learning.