How to Comment Your Code Like a Boss

Featured on Hashnode
Featured on daily.dev

Subscribe to my newsletter and never miss my upcoming articles

Comments are like garlic.

They can push a dish over the top. Or, they can relegate it to the polite pile of leftovers that your guests appreciate but didn't enjoy.

Comments in your code are much the same. Good, clear, and necessary comments can help keep an otherwise convoluted narrative of code become a clear, easy-to-follow story.

The two main ideas that have helped me when deciding if a section of code needs comments, or if I should leave it bare are these:

πŸ’‘ Code should explain what is happening.

A true gem from Uncle Bob's Clean Code is the chapter on naming. Explicit and clear naming will help make your code be clear and easy to follow.

Instead of this:

// get the length of an array
const gl = a => a.length

We write this:

const getArrayLength = a => a.length

This allows us to write code that is expressive. The code itself tells you what is happening. In the simple example above, the name of the function tells you what it does. There is no need to parrot this in a comment above. Each time you write a comment, you add to the mental overhead of trying to parse not only the code, but the comments as well. This is why comments should be limited & meaningful.

πŸ’‘ Comments should explain why.

Let's say we have a user base that is split between two databases. A client or product has users from an old system, a new system, and our application needs to manage both while we transition the code base to a new platform.

import oldsdk from 'old-sdk';
import newsdk from 'new-sdk';

const getUserByEmail = async email => {

    // we switched identity providers
    // and not all users are migrated yet.
    const oldUserData = await oldsdk.getUserByEmail(email);
    const newUserData = await newsdk.getUserByEmail(email);
    return newUserData || oldUserData;
}

In this example, we are fetching a user from some API using a new SDK, and an old SDK. Stuff like this happens all the time. For someone reading this code, while the variable names are descriptive, we don't know why this is happening. The comments in this code explains the purpose of this code. The what is still clear.

Conclusion

Like many things, this is not a hard and fast rule. In fact, it's not even a rule, but more like a tool. It's a generalized guidepost that has been helpful for me in my career as a barometer for writing good comments. There are plenty of situations where you would want or need to approach things differently, but this tip can be a great starting point when getting a feel for writing comments.

Happy coding!

Szymon Adamiak's photo

"Comments are like garlic." landed in my notebook ;)

Good read!

Show +1 replies
Szymon Adamiak's photo

Chris Arter I track almost everything I need in Notion. For longer texts, I use Google docs and link them to Notion.

Also, there is my shameful secret. For quick notes, I use the built-in ios app. Now it's a definition of spaghetti, only I can understand anything ;)

Chris Arter's photo

Szymon Adamiak

Now it's a definition of spaghetti, only I can understand anything ;)

Encryption-at-rest πŸ˜‚

Rahul's photo

This post was like how to read this post like a PRO.

Ernesto Angulo's photo

Awesome! Thanks. πŸ˜€πŸ˜€

Chris Arter's photo

Thanks Ernesto!

Tim Hanke's photo

Nice clear breakdown of what/why. This makes a lot of sense. Thanks.

Chris Arter's photo

I'm glad you got some value from it, Tim!

Tijan Ayomide's photo

Awesome article πŸ‘... I really like the analogy comment are like garlic πŸ˜ƒ

Maxi Contieri's photo

amazing article !

I'll use your garlic analogy from now on :) PS: I'd add that comments are not always maintained but unlike automated tested code.

Julio Molina's photo

Very nice read! Thank you Chris. As a beginner I want to comment everything but this has given me a better understanding of comments.

Torsten Curdt's photo

The why but also the how. And ideally from higher level view. I wrote an article about this a loooong time ago. While the focus at the time was java, it is the universal approach that is important - and timeless.

Peter Singh's photo

What do you make of using JSDoc's in with commenting on code, I found this out early on when I started using VS Code, and I have personally found that it has helped me out enormously as it works well with intelliSense.

an example,

/**
 * @function distanceBetweenPoints
 * @description
 * Takes the cartesian distance between two points A(x,y) and B(x,y) 
 * 
 * @param {Number} x1 - X - Co-ordinate of the Primary Object
 * @param {Number} y1 - Y - Co-ordinate of the Primary Object
 * @param {Number} x2 - X - Co-ordinate of the Secondary Object
 * @param {Number} y2 - Y - Co-ordinate of the Secondary Object
 * @returns Distance in Pixels
 * 
 */
function distanceBetweenPoints(x1, y1, x2, y2) {
    return Math.sqrt((x2 - x1)** 2 + (y2 - y1)**2)
}

I understand your claim that comments should be used to provide a narrative to the code, where it doesnt require additional overhead to 'parse' both comment and code, this example would definately run foul of that command, but by decalring it once, using it through the IDE, I can look up the meaning behind the function which provides clarity when Im using them through the script.

So is using JSDocs a good thing or a bad thing in respects to 'Comments are like garlic'...?

Thanks for the great article, definately got me thinking if Im doing things wrong.

Show +5 replies
Nate Osterfeld's photo

Peter Singh Ohh this looks like it would be fun to make. Couple of unwarranted criticisms, although I'm sure you're aware.. You can't shoot while moving, I don't think this is intended? And also, some settings would be really awesome, as well as useful.

Right now it's really hard to control because of how fast the thing spins, so sensitivity would be 1 setting. Another would be to add different styled spaceships (colors, shapes, etc.). Not only would this simply be cool, but it's often confusing trying to discern which point of the triangle is supposed to be the front. A quick fix to this could just be changing the colors of the borders in the front/back as well as narrowing/widening the triangle so it's more blatant which way it's facing.

Just some ideas, though! Super cool regardless(:

Peter Singh's photo

Nate Osterfeld all excellent ideas man, thanks for that I really appreciate the feedback. If you bear with me i'll see what I can put together. I really like the idea of settings for sensitvity, I think I can go futher and add a few more settings. That would be an interesting exercise. First thing Ill do tomorrow is look into why its not shooting while moving. (it really should...) And thank you for playing man, Im really happy that you guys liked it.