DEV Community

Discussion on: Commenting: where?

Collapse
 
nombrekeff profile image
Keff • Edited

For me it's above, so it follows the flow of the code.

But I strive to use the least amount of comments posible, as mentioned in other comments, code should explain itself. For me comments should explain why, not how. Why are we doing this in this particular way.

Comments are also another dependency to take care of when refactoring or modifying code. You must keep them updated with the code, otherwise they only add confusion and uncertainty. Should I trust the code or the comment? (the code of course)

Then it also depends on the standards of the codebase, maybe there is a standard define alreay, which you should follow. Otherwise it does not matter at all, meanwhile you're consistent.


Useless comments:

class User {
  // Returns the name of this user
  getName() {
     ...
  }
}

------

const name = user.getName(); // Get the user's name

const sum = a+b; // Sum the two values together
Enter fullscreen mode Exit fullscreen mode

As you can see these comments are useless as f*. They offer no value at all, just adds noise. You would be surprised at the amount of comments I've seen over the years following this line.

Now let's see some useful comments

public ensureCurrentItemIsOnList() {
    // This code is needed because if, in the first load, there is no `this.item` it would not be shown in the selector
    // So if `this.item` doesn't exist in the list we receive, we just add it to make it appear on the selector
    // This way we can list 10 items initially without problems, otherwise we should list every single item, which is not feasable
    if (this.item && !this.items.some((it) => it.id == this.item.id)) {
        this.items.unshift(this.item);
    }
}
Enter fullscreen mode Exit fullscreen mode

I could go on for quite a bit on this topic, so I will stop here for now. Might write an article on this if I find the time...

Collapse
 
vulcanwm profile image
Medea

Nice!