DEV Community

Cover image for To comment or not to comment?
Dan Newton
Dan Newton

Posted on

To comment or not to comment?

I recently had a quick look at the first blog post I ever wrote, Should you write comments?. This triggered me to question whether I still take the same stance around comments that I did when I wrote the post (over two years ago now).

I am not 100% sure where I stand now. I still think that pretty much everything I wrote is what I do nowadays. But, I think there are a few more situations now where I am willing to use comments.

While I spend a bit more time thinking about this myself, I think it is worth seeing what you all believe when it comes to writing comments. Maybe then, I can better collate my thoughts and possibly write a follow-up post that documents what I do now and what caused me to change my opinion.

So, should you write comments?

If so:

  • When do you write them?
  • What do put in them?
  • Where do you put them?
  • Do you think you can write too many comments?
  • Are there times/projects where comments are more important?

And if not:

  • Why not?
  • What do you do instead?
  • Are there times where you have been tempted to write comments

Top comments (25)

Collapse
 
dbanty profile image
Dylan Anthony

I find that comments are more useful for explaining why rather than how or what. Your code should be readable enough for people to know what it’s doing, but sometimes the reason isn’t obvious.

Like if you’re working around a limitation of a library you’re using. Or you’re working around some old code (technical debt) that you can’t refactor now. Yes I know ideally you’ll immediately fix all the problems in a codebase instead of working around them, but that’s not always realistic. So sometimes you need comments to make the code make sense.

Collapse
 
lankydandev profile image
Dan Newton

100% agree with that. I think that is the happy medium. Most of the time you don't need, since your code explains it. But for those times where it isn't enough, the comments back it up.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Write as few comments as possible. The code should be readable on its own. Use good symbol names and structures.

Reserve comments for things that are not expressed in code well, and keep them minimal. Unlike code, there is nothing checking that comments are correct, thus tend to get stale. Thus focus on information that won't likely get stale.

Collapse
 
laurieontech profile image
Laurie

I think comments are essential for code snippets that were hard fought. If it took you considerable time to design and implement, its worth explaining what is happening there.

Strong naming conventions and clear delineation of logic does not act as a substitute for a quick roll up explanation.

Future you, or anyone else, shouldn’t need to read the entire function (and any other abstractions) to know what the code is doing and controlling.

Collapse
 
lankydandev profile image
Dan Newton

How strong is your emphesis on hard fought here?

Are you only talking about longer functions / functions that are doing really complex stuff? Or do smaller / simpler functions also warrant comments?

Basically, how far do you think we should take this and at what point is naming no enough and comments need to step in?

I'm not disagreeing with you, I think I have actually been gravitating to what you just said. Although I do not document private functions to often and instead normally comment on inside if it is doing some funky stuff. Maybe that is something I should change.

Collapse
 
laurieontech profile image
Laurie

It’s definitely based on personal discretion.

I think hard fought code that results in a simple solution doesn’t necessarily need a comment. But code that wasn’t intuitive to write is probably not intuitive to read, so that context and explanation is helpful.

Collapse
 
laurentiu-dancu profile image
Laurentiu Dancu

I personally encourage my colleagues to write as few as possible comments. I call such comments 'excuses'.

When I read a function or method signature it should be immediately clear to me what that function or method does, how it should be use and what's its purpose. I shouldn't have to know any details about the implementation to use it. Virtually any function can be designed with such clarity in mind.

A similar approach can be attempted for implementation. Any code contained in a function 'worthy' of an 'excuse' can be refactored into another function with clear intent and purpose. I don't care that it will be called in a single place if it brings clarity.

Of course, I allow 'excuses' if the offending piece of code is not the developer's fault, like with strange business logic or partial solutions based on incomplete information. My point is that comments shouldn't be used liberally. Code can and should be written with clarity in mind, especially if you share the codebase with lots of other devs.

Collapse
 
lankydandev profile image
Dan Newton • Edited

Agreed. Not much is more annoying than a function which leaves you more confused after reading its name or does something different to what it says it should!

Collapse
 
xlebenny profile image
Benny Leung • Edited

I love function name / variable name like a comment,

It can easily to read like a flowchart,
And comments

public static Coffee CreateCoffee(
CoffeeTypeEnum coffeeType)
{
    var coffee = new Coffee();
    var shouldAddMilk = IsNeedMilk(coffeeType);

    if (shouldAddMilk)
    {
        coffee.Add(Milk);
    }

    coffee.Add(Espresso);

    return coffee;
}

But if you have any technical issue / temporary fix / some business walk around
It should be write a command, create some tickets and fix it

private bool IsNeedMilk(CoffeeTypeEnum coffeeType)
{
    // FIXME #123 MilkFoam shouldn't is a type of Coffee
    if (coffeeType == CoffeeTypeEnum.MilkFoam)
    {
        return true;
    }

    var result = MilkCoffeeTypes.Contains(coffeeType);
    return result;
}
Collapse
 
appeltel profile image
Eric Appelt

I write docstrings.

I learned to use docstrings in python and naturally use them because I work mostly in python currently. But if I reverted back to C++ or another language that has no built in support for docstrings, I would still try to write "comments" formatted like a docstring. A docstring is a bit of definitive and explanatory text that accompanies the declaration of a function or other object. Quoting python standard PEP-257:

The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its init method. Individual methods should be documented by their own docstring.

Every "public" class, function, or method gets a docstring that conforms to the above.

I've heard in many places that the name and call signature of a function should be self-explanatory of how to use it, and the code should be self explanatory as to what it does. But if you think about it, this is an extremely tall order in most cases, especially when code is written under a deadline.

One of the major benefits of factoring code out into small functions (ideally without side-effects) is that the developer doesn't have to handle the cognitive load of what all of the application code does all at once. So even if code can be reasonably described as being self-explanatory, in the absence of docstrings or comments the developer still has to read and understand how the function does what it does when all they really needed was to know what it does. This is a distraction from the developer's task at hand - writing the calling function and understanding it's internal state.

Additionally, following a common format for docstrings on all functions opens the door to automating the generation of API documentation. This is particularly useful as it is much easier to ensure that documentation of the API is up to date when it is right in front of you whenever making a change to a function or method.

As far as actual non-docstring comments, I rarely write any and they usually describe the why behind something that came up in some subtle edge case, just to make sure any further modification takes note of the special problem, i.e. "# We need to detach foo before linking quux in cases of network congestion, see ticket 38745".

Collapse
 
gilblinov profile image
Gil Blinov

Something that wasn't brought up here is writing comments after code has been written and in production.

I'm talking about the need to revisit code due to bugs, refactoring or when the code you're writing now needs to use it.

In these cases, when you don't immediately understand the code and need some mental gymnastics to grok it, instead of writing notes to yourself - do so in comments.

My personal recommendation is to use markdown in a code block to go through the thought process. In some cases I even added flowcharts or sequences using mermaid.js

Usually, this is also a good indication that the code needs to be refactored. Until it happens, your comments will help you or someone else who will need to revisit this code in the future.

Collapse
 
rendall profile image
rendall

Any hard rule about this will slip quickly from "helpful convention" to "torturous ideology".

Use comments to explain why a piece of code is doing what it's doing. Or to help organize thoughts. Or to document public methods for tooltips. And do it consistently, unless that doesn't fit, then do something else.

But heaven's sake, please do inject jokes and humor into your comments. I distrust teams that are against this.

Collapse
 
lankydandev profile image
Dan Newton

I misread the last paragraph the first time I read that which gave me a completely different impression of you 😄

Collapse
 
erelguitars profile image
erelguitars

Ideally only the public methods should have a method comment. Private methods may have a method comment and only use inline-comments if really not understandable. All the rest is about proper naming of Classes/Methods/Properties/Variables, separations of concerns and methods as short as possible (they should do one thing only). But thats the ideal case of code...

Collapse
 
danielhutchinson profile image
Daniel Hutchinson

I use them as a design tool.

I tend to only write comments when designing, it's my way of thinking out loud. Stating what I want to achieve before writing any code. I then replace these comments with the actual implementation.

A trick I learned from another Dev at my day job is to write comments at the top of my classes to explain what they do, if I put the word "and" in there then I know the class probably does too much. Then I delete the comment (or sometimes just do this in my head)

Collapse
 
lankydandev profile image
Dan Newton

I comment code to note down what I want to do as well. The problem I used to have was deleting these comments before committing :(