Abhishek Kumar

Writing Better Comments in Code

"Understand how to write meaningful and helpful comments that improve code readability and maintainability."

Abhishek Kumar

Table of contents

    Writing comments in code is a fundamental yet often overlooked aspect of good software development. While code should be self-explanatory, well-placed comments can drastically improve clarity and make future maintenance easier.

    🤔Why Comment at All?

    • Explain why something is done, not just what is done.
    • Help teammates and your future self understand complex logic.
    • Reduce onboarding time for new developers.

    ✅Good Commenting Practices

    1. Focus on the “Why”

    Bad:

    i++; // increment i
    

    Good:

    i++; // Move to the next item in the array
    

    2. Keep Comments Updated

    Outdated comments are worse than no comments. If the code changes, so should the comment.

    3. Avoid Redundant Comments

    Don't repeat what the code already tells.

    Bad:

    # Add a and b
    result = a + b
    

    Good:

    # Combine user's previous and current scores
    result = previous_score + new_score
    

    4. Use TODOs and FIXMEs

    // TODO: Refactor this to a reusable hook
    // FIXME: Handle API error correctly
    

    Use them consistently so others (and your tools) can track unfinished tasks.

    💡Types of Comments

    • Inline comments: Short, next to a line of code.
    • Block comments: For explaining a logic block.
    • Docstrings: For describing functions, classes, and modules.

    Example in Python:

    def add(a, b):
        """Return the sum of a and b."""
        return a + b
    

    ✨Tools That Help

    • ESLint or Prettier: Can enforce comment style rules.
    • VS Code extensions: Like “Better Comments” to color-code different comment types.

    🔚Final Thought

    Good comments make good code great. They're not just for others—they’re for you six months later, wondering what you were thinking.

    Write less, but write clearly. Comment with purpose.