ProgrammingJavascriptCareerProductivityGadgetsASP.NETSecurity

The Art of Code Comments: Writing Clean and Effective Explanations

Written by
Published on
Filed under
The Art of Code Comments: Writing Clean and Effective Explanations

Have you ever looked at a piece of code that you wrote eons ago and wondered what you were thinking? Or even wondered if it actually worked? Code comments are like little time capsules of your thoughts, providing future you (and your fellow developers) with insights into the logic and intentions behind your code.

// complex logic for sales system with 3 params
function complexSalesOrder3rdEdition(p1, p2, p3)
{
   ...
}

In this article, we're delving into the world of code comments – those lines of text that don't affect how your program runs, but play a crucial role in understanding, maintaining, and collaborating on your codebase.

Whether you're a junior developer just starting out or a seasoned coder looking to refine your practices, mastering the art of writing clean and effective code comments is a skill that can significantly elevate the quality of your work.

Why comments matter

Let's start here, because context is important when it comes to determining what good versus bad comment entails. People either comment sparingly when the mood arises and if they remember to, or they comment every single line of code that they type regardless of what's happening.

And usually, the magic is found somewhere in the middle. So why do 'good' coding comments matter at all?

Collaboration - Whether you work for a startup with 3 developers or a large company with 300, someone is going to have to read your code at some point in time. And you're going to have to read somebody else's. And every developer, for the most part, codes differently. They have different ways of writing algorithms, or naming variables or even in how they refactor their code.

You might find that the variable that you're looking for is set 3 layers up in some strange component titled 'mainComponent', without any further context. And if you're lucky enough to work on that particular code, it might take you a while to figure the whole thing out.

Assume a team mentality when working on a corporate codebase and write every comment as if you're explaining it to your non-technical project manager.

Compliance and Regulations - This might not apply to you currently, but depending on the industry that you work in and just how much sensitive data you deal with at work, you might be under the lens of security and compliance audits from time to time.

And while these audits don't necessarily police for comments, we can't really assume that they never will.

And on the other side of things, having poor comments with personal statements, jokes and database passwords probably isn't going to help things either.

I've worked at companies where production passwords were kept in comments (assuming by error) and which were deployed to a public website. Needless to say, it was caught by IT relatively early on and fixed, but not without new policies being put into place.

Educational Purposes - Many companies have junior developers on board with only a few years of experience and a big part of them being as effective and engaged as possible is having good standards for them to follow.

Comments can help explain more complex logic that perhaps a junior dev might not be familiar with just yet. Not only can comments help in understanding these topics, but they can also help to reduce the occurrence of bugs from younger developers.

And having younger developers comment code themselves can help during code reviews.

Personal use - Having to come up with a concise sentence explaining some concept on the fly can be beneficial for you as well. 

// function that generates a new sales order record, and creates 'n' child items
function generateSalesOrder(items){
...

Often times that's where I personally start when coming up with the logic to a complex function. At least while they are there, these comments can help to keep you on course with what you are currently doing. More often than not I end up changing these comments to something completely different once I am done working on the code.

If the code is being worked on and not yet ready for production though, I personally also will add reminders and todo statements for when I pick up coding the next day.

// reminder to encrypt data and send email receipt

When that particular function is complete, I typically will remove that old comment and replace it with something more meaningful to the rest of the team.

Strategies for Writing Effective Code Comments

There's no technical right or wrong way of writing comments in code. If the statements make sense to you and to your team, then you're doing a good job. But if you aren't used to writing comments, then here's a few strategies that you can use to get started.

Be clear and concise - The whole point of the comment is to reduce the chance that somebody is going to misinterpret your code. It isn't to gauge your quality of work or anything. So using simple natural language is important. Assume that developers will read your code and that they already know the technical portion of what's happening.

You don't have to keep it to one sentence either. I'd personally rather see 2-3 sentences that make clear logical sense, than one short statement that doesn't quite fully explain everything.

// Using a linear search here for simplicity
// consider optimizing if list size increases
for (int i = 0; i < numElements; ++i) {
    // ... linear search logic ...
}

Address any assumptions - And by that I mean, there should be no assumptions left to make. Often times logic in code isn't as clear as 1 + 1 = 2. Sometimes you have to multiply the result by .3 in order to 'fill in the gap reason'. And that should be addressed in the comments section.

// send a max of 3 suggestions per user (meeting w/ sales 1/1/2023)
function sendSuggestions(userid){
 ...
}

Situations like these are super common in the workplace, particularly as you work closely with marketing, sales and business teams. And as things change throughout the months, comments are going to help you figure out why these random values keep changing.

Use a consistent style - In order to maintain readability, for both yourself and others, consistency is important. I personally initialize my comments and date them so that others know how recent changes were made and who made them without having to look at a changelog.

// walt - updating query to include inactive users (9.1.2023)

Regardless of how you format your comments, or what data you choose to include, having consistency across a development team makes writing comments less of a chore, as you don't have to reinvent the wheel every single time.

Avoid obvious comments - There's a certain percentage of developers out there that feel that the more comments the merrier. And they write equally as many comments as lines of code, which can definitely clutter up the codebase and turn a 100-line script into a 300-line maze of green or light gray.

Ideally, if you're writing good solid clean code with a strong naming convention, you won't need to include a comment. The code itself should be self-explanatory in most cases.

// function that sends recommendations to a user
function sendRecommendationsToUser(){
...

Add revisions - Much like code, comments also need to change from time to time. Particularly if there are changes in the code, but also if the comment itself just hasn't evolved that well. Maybe it was missing logic, or some part of it kept confusing teammates.

Updating comments can be just as important as updating an old outdated function in your code. Because as logic changes, so too will the comments used to describe those changes.

Common Mistakes to Avoid in Code Comments

Remove outdated comments - If the logic in your application has completely changed in some way, yet there is a comment somewhere still referencing the old logic, it should absolutely be removed. This can cause confusion to somebody that is unaware of the change, such as a new employee.

Avoid redundant comments - Leaving a comment just for the sake of leaving a comment is never a good idea. It clutters up the codebase and adds needless lines that a developer in the future will have to scroll through.

// function that saves a note
function saveANote(note)
{
...

Comments typically trigger curiosity from a programmer. They see the green line and assume that something is up, and that they need to read to figure out just what is happening. But if most of the comments are essentially just a repeat of the function names, then most programmer's will quickly get bored and stop reading them altogether.

Lack of context - If only you can understand your comment, then it probably isn't too effective.

// update number of retries

In this particular comment, there is probably a reason why the number of retries needs to be updated. And there's also a value that you are updating it to. But none of that is clear from the comment. While it might make sense to you the day that you wrote it, 2 months from now, you're going to wish you remembered what it even means.

Poor formatting - While everyone has their own style when it comes to writing code and comments, comments should be kept simple without any extra fancy formatting.

// ******************* title goes here **********************
// *item 1
// *item2
// etc...

No one wants to read a paragraph or giant bulleted list of items repeatedly when trying to debug code. And if there's a chance that someone might not read those comments, then they aren't serving their purpose.

If your company already has standards set in place, then be sure to follow those of course. But if you're sort of free to come up with your own formatting, I always advise that simple is better.

Making it personal - Sometimes a developer encounters somebody else's code and they may not fully understand what is going on in it, so they may leave the following:


// bob - unclear what this function does...
function sendSecondarySequenceEmail(){
...

And fair enough to Bob, because yes it can be frustrating to encounter an important method in an application with little to no explanation on what it means.

And I personally have seen these type of comments many times during my career. But they don't help in any way and just create tension in a place where tension should not exist. The code.

Don't take it personal, and don't make it personal, is my advice here.

In closing, adding comments to code sounds like a simple process. But as you can see from the list above, there's a bit more to the whole thing that most developers don't often think about. I've personally have seen it all when it comes to 'bad comments' during my career.

These annotations are your allies in understanding, collaboration, and long-term code maintenance. By writing clear and thoughtful comments, you're not just documenting code – you're helping your future self and your team. So, go forth armed with the knowledge that every comment you write brings clarity to the complex dance of ones and zeros. Happy coding!

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks