How to Write Effective Code Comments

Selvin Ortiz

7 months ago

Most people who write code are not good copywriters, which is why most code comments in the wild are poorly written.

Taking the time to write clear, concise, and effective comments is a vital part of being a professional developer.

That said, many of you will disagree with my philosophy that by default, I don't write code comments.

I push my code to communicate my intent as far as I can before I reach for a comment.

Anatomy of a Code Comment

A good code comment has three essential parts:

  1. Context: What is the comment explaining? Is it describing a function, a variable, or a block of code? Provide the necessary context to understand what the comment is about.

  2. Purpose: Why does this code exist? What problem does it solve? What is its intent? A good comment should explain the rationale behind the code, not just reiterate what the code is doing.

  3. Clarity: Use simple, straightforward language. Avoid jargon, abbreviations, and ambiguity. The comment should be understandable to anyone reading the code, not just those familiar with the codebase.

A few examples

Retry with backoff in Go.

// This helper function implements the exponential backoff with jitter strategy
// to retry a given operation with increasing delays between retries, up to a
// maximum number of attempts. It is useful for handling intermittent errors
// or transient network issues.
func retryWithBackoff(operation func() error, maxAttempts int) error {
    // ...
}

Regular expressions in PHP

// This regular expression pattern matches email addresses with specific requirements
// to ensure better validation than the standard filter_var() function.
$emailPattern = '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)(?:\.(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-

Shopping cart functionality in JS

/**
 * Calculates the total cost of a shopping cart, taking into account
 * any applicable discounts and taxes.
 *
 * @param {Object[]} items - An array of items in the shopping cart
 * @param {number} discountPercentage - The discount percentage to apply
 * @param {number} taxRate - The tax rate to apply
 * @returns {number} The total cost of the shopping cart
 */
function calculateTotal(items, discountPercentage, taxRate) {
  // ...
}

These comments provide context, purpose, and clarity.

When to Write Comments

Not every line of code needs a comment. In fact, over-commenting can make your code harder to read and maintain.

Here are some guidelines for when to write comments:

  • When the code cannot communicate your intent: If the code's purpose or functionality is not immediately clear from reading the code itself, a comment can provide valuable context.
  • Before complex or tricky sections of code: If a piece of code is particularly complex or relies on obscure language features or algorithms, a comment can help explain what's going on.
  • For public APIs and interfaces: Public-facing code should be well-documented to help other developers understand how to use it correctly.
  • For temporary workarounds or hacks: If you've had to implement a temporary solution or hack, a comment can explain why and when it should be revisited or removed.

Comment Writing Mistakes

Even well-intentioned developers can make mistakes when writing comments.

Here are some common pitfalls to avoid:

  • Redundant comments: Don't just reiterate what the code is doing – explain the "why" behind the code, not the "what".
  • Outdated comments: Failing to update comments when the code changes can lead to confusion and misinformation. Keep comments in sync with the code.
  • Excessive comments: Too many comments can make the code harder to read and maintain. Only comment when necessary.
  • Unclear or ambiguous language: Use clear, concise language and avoid jargon or abbreviations that may be confusing to others.
  • Incorrect formatting: Follow consistent formatting guidelines for comments to improve readability and maintainability.

Final Thoughts

Writing great comments is an essential skill for any developer. It takes practice and discipline, but the effort pays off in more readable, maintainable, and collaborative code.

Remember to focus on providing context, explaining the purpose, and using clear language. And don't be afraid to revisit and refine your comments as your code evolves – after all, good comments are living documentation that should grow and change with your codebase.

Selvin Ortiz at desk

Who wrote this article?

Selvin Ortiz👋

I'm a software engineer and content creator.
I help brands develop software and content strategies 🚀

On this blog, I write about software development, emerging technology, technical leadership, and content creation ✨

My Most Recent Posts

My Most Recent YouTube Videos

Subscribe to My Newsletter 💌

Delivered straight to your inbox once a month. I’ll send you a curated list of my latest content, top tech tips, and exclusive insights.

Once Monthly
I’ll email you a curated list with my latest content and best tech tips.
No Spam
I pledge to never share or sell your info, and will never send you junk.