DEV Community

Cover image for You should write a comment on every line of code
Nočnica Mellifera for Heroku

Posted on

You should write a comment on every line of code

How many times will your code be read?

In a successful product, code will be run thousands or even millions of times. Each time an interpreter will read your code (please do not comment on my metaphor). We all know that it’s worth the time to write code that runs efficiently on its machine. Have you ever stopped to ask how many times will a human read my code?

Because I think the answer is a lot.

Most successful code keeps running in a product somewhere long after you might have guessed. There’s 20-year-old code running in at least one of the web sites you visited today. And while your code might well be interpreted by countless contractors, junior devs, and new hires trying to figure out your codebase; there’s one person who’s the most likely person to be rummaging through your code next year, desperate to figure out what it does and why it does what it does.

You.


However well you think you understand what you’re working on right now, the realities of human memory means anything you come back to weeks later likely won’t feel familiar.

Code comments mean leaving yourself a map

And that feels silly, right? Why would you need a map? You built this place! It feels silly. I assure you that you will need this map someday.

A couple of code commenting basics

I should make two points that I often have to cover with beginning programmers.

  • Comments do not and cannot impact your code’s performance.

The actual machine that runs your code will completely ignore comments, it’s why we have to mark comments with special characters. Adding a whole novel’s length comment above every function will not slow your code’s execution by a picosecond.

  • Long comments are very easy to hide

When you’re starting out with your code editor you might find extremely long comments quite annoying to scroll through to find the code you need to work on. But once you have some experience with your editor you should be able to ‘fold’ comments so they disappear when you don’t need them

code unfolding

A lovely gif of code folding in Visual Studio Code by Bill Souror

If you’re struggling with way too many visible comments, search for a tutorial on how to hide them, or even hide them by default, in your chosen code editor!

Code comments are not code smell

An attitude I see quite a bit is that comments, especially long comments, are ‘code smell.’ Meaning they indicate your code may have problems. I absolutely disagree with this.

The standard example is something like:

var x = user.info3 // this stores the user’s age

And this indicates a problem because it would be better to just name the variable userAge instead of x with a comment. That’s a fair point in this contrived example, but this ignores by far the most common use case for comments. Comments rarely explain only what’s happening in the code comments explain the larger context—the why—of what our code is doing.

While it is possible, though not always convenient, to rewrite your code so that its internal workings are easy to figure out, it is not possible to explain that you’re doing something in an odd or un-intuitive way because of concerns outside of the code.


//this code checks if the account creation date 
//was in 1911 since this (impossible) creation year 
//was used to indicate that these users were  
//imported from the old DB with no creation date set. 

A comment like this one explains code behavior that will never make sense without some kind of documentation!

How to write fewer comments

So, we admit that there are some comments it’s almost impossible to do without. If we really hate writing comments, what’s some way we can do it less?

Probably the most common solution is breaking up functions into smaller functions. A few lines inside the function updateUser might need a comment, but those same three lines inside a separate function named setUserScoreToZero probably needs no comment, this code sets the user’s to zero, ‘nuff said!

Again, this doesn’t get us away from the problem listed above: function names can’t explain external factors. It can also result in longer and longer function names. While code comments are easy to hide, super long function names you’re just kind of stuck with! This certainly doesn’t mean that many small functions, descriptively named, are worse than code comments. It’s just that there are tradeoffs!

But you should be writing more comments

Sorry for the clickbait title, but really, you should be writing more comments, a lot more. Every line? Probably not. Here are the lines you can skip:

  • Variable declaration (If you set a good variable name)
  • Function declaration (again, good names)

That’s it! Those are the only lines of code you can always skip commenting, everything else might need a comment sometime.

Kindness is key

I won’t link to it here, but a lot of the justifications I see for programming antipatterns amount to ‘if you can’t understand/use this style of code, you shouldn’t be coding at all.’ Whether this is valid or even cogent criticism I’ll leave to one side, only to say that thinking like this is unkind. And when given the choice I will always make design choices that start with kindness.

Every time I take the time to define something I think everyone knows, I tend to get a few thank you comments. Better yet, it just feels better to leave some code comments or write some documentation knowing it might help someone someday—perhaps even the future you. It feels a lot better than tearing my hair out because “no one understands my genius code!”

When we write code comments we are making a promise to our future selves. We don’t know if this code will get reused for decades or languish in obscurity. But if the time comes and these source files are opened again, we will be there. We will offer our help. When we wrote this, here is what we were thinking, we hope it makes sense, we tried to help. Good luck.

Top comments (8)

Collapse
 
scottshipp profile image
scottshipp

I understand the desire to propose a dogmatic and extreme point-of-view around things like comments. But it isn't helpful to say "never write any comments" any more than it is helpful to say "comment every line" in my opinion. The truth is somewhere in the middle. And I personally think that because human psychology is what it is, you should first try to write code without comments and ask yourself if it is as clear as it can be, then refactor to something clearer, before you write the first comment. And I agree that any comments you write should be "why" comments as opposed to what I see far more often which is "how" comments. The code is telling you "how" the application will handle some use case. The "why" is more important.

Collapse
 
alainvanhout profile image
Alain Van Hout

Comments can help to add explanation where needed. When you add them all over the place, it's however much harder to recognize the really important information among all the noise.

Collapse
 
waylonwalker profile image
Waylon Walker

This is why I like python.

  1. Typically when I have a line that I need to comment on, I find that refactoring is necessary, then it almost reads as pseudo-code, and doesn't need a comment that needs to be updated with the code.

  2. It also has a very good practice of making good clear docstrings that find there way into the documentation, and help text. This is where you tell users of your code how to use it, what it does (high level), and why. It does not need to be fully detailed, your code should be the details. realistically many libraries have more docs than they do code. especially when you add up all of the examples. But they do not document each line x=10 # setting x to 10

Collapse
 
davidjames profile image
Info Comment hidden by post author - thread only accessible via permalink
DavidJames

I have no idea how you supported the idea but I don't allow it on my team (commenting every line). Are you nuts? Maybe it's different for a team that mostly focuses on the back-end but I doubt it. Properly named variables and functions along with well formatted code (the IDE should do this for you) serve as their own documentation 90% of the time (in my 25+ years of experience). Comments are more for blocks of code, e.g. "this bit does X", then you should be able to take it from there by reading the code itself.

Collapse
 
leob profile image
leob

Completely agree, comments are documentation, and documentation is good - it's as much part of the "product' as your code itself is.

I add comments to functions (or other pieces of code) whenever it is not immediately obvious what that function is doing, why it is there, and what its role "within the whole" is.

Whenever I've sourced solutions from StackOverflow or other places I also often add a URL to the source location as a comment.

Collapse
 
leob profile image
leob

Agree to all that, in the first place your code should speak for itself. However there can always be context outside of the code, which is the point about explaining the "why" in a high level comment.

And yes if you have unit tests then that's definitely living documentation, if written well (I've seen unit test code which was an overcomplicated mess, in which case it was not really helpful as documentation).

Collapse
 
matthewbdaly profile image
Matthew Daly

I think comments are generally useful, but should be a last resort for explaining how something works.

DocBlock-style comments, for instance, are a poor substitute for actual parameter and return types. Where possible one should always set explicit parameter and return types in preference to setting them in a DocBlock, as these will be enforced by the language and so can't get outdated without explicitly breaking the response. For languages that don't support these, there are often other solutions, such as Flow in Javascript.

Collapse
 
nocnica profile image
Nočnica Mellifera

I like the idea of tests as documentation!

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more