·

Best Practices for Writing Code Comments

Best Practices for Writing Code Comments

Over the years, working on diverse development teams has taught me the immense value of effective code commenting. While clean code should ideally explain itself, well-crafted comments are indispensable for providing context and ensuring maintainability.

I follow some guidelines to keep things clear and helpful.

1. Prioritize Clear Code

First and foremost, strive to write self-explanatory code. Good naming conventions, consistent formatting, and logical structuring reduce the need for excessive comments. In my experience, the best codebases have minimal comments because the code itself is so clear.

ts
// Bad let x = 42; // Maximum number of retries // Good let maxRetries = 42;

2. Explain the "Why" Not the "What"

Comments should add value by explaining why certain decisions were made, not merely describing what the code does. This is crucial when working on complex projects where understanding the rationale behind decisions is key.

ts
// Bad let discount = price * 0.9; // Apply 10% discount // Good let discount = price * 0.9; // Promotional discount for Black Friday

3. Keep Comments Up-to-Date

Outdated comments can be detrimental. I've seen teams struggle with legacy code where comments were never updated, leading to confusion. Always update comments when the code changes to keep everything aligned.

4. Avoid Redundant Comments

Comments should not state the obvious. When working on large projects, redundant comments can clutter the codebase and distract from more important annotations.

ts
// Bad let total = a + b; // Add a and b // Good let total = a + b; // 'a' and 'b' are user-input values

5. Use Consistent Style

Consistency is key, especially in large teams. A uniform commenting style helps maintain professionalism and readability. Whether you're using // for single-line or /* */ for multi-line comments, consistency helps everyone quickly understand the code.

ts
// Calculate the area of a rectangle function calculateRectangleArea(length: number, width: number): number { return length * width; } /* * This function calculates the area of a circle. * The formula used is π * radius^2. */ function calculateCircleArea(radius: number): number { return Math.PI * radius * radius; }

6. Comment on Public Interfaces

When writing code meant to be used by others, such as APIs or public classes/functions, provide clear documentation. This helps external users understand how to interact with your code.

ts
/** * Fetches user data from the server. * * @param userId - The unique identifier for the user. * @returns A promise that resolves to the user's data. */ async function fetchUserData(userId: string): Promise<UserData> { // Implementation here... }

This also applies to large codebases, it helps teams to quickly understand how to re use code written by other team members.

7. Minimize the Use of Abbreviations

I've found that abbreviations can confuse, especially for new team members or external contributors. It's better to spell things out unless an abbreviation is universally understood.

ts
// Bad // TODO: Impl. caching logic // Good // TODO: Implement caching logic for improved performance

Avoid abbreviations unless absolutely necessary, as they can hinder readability.

8. Avoid Overloading Code with Comments

Too many comments can be just as harmful as too few. Focus on adding comments where they truly add value. In my experience, teams that over-comment tend to have messy codebases.

ts
// Bad let sum = 0; // Initialize sum for (let i = 0; i < numbers.length; i++) { // Loop through numbers sum += numbers[i]; // Add number to sum } // Output the sum console.log(sum); // Print sum

9. Use TODOs Sparingly

TODO comments should be clear and actionable. They are helpful for tracking pending work but can become clutter if overused. Always specify what needs to be done and why.

ts
// TODO: (Chris) Optimize this function for handling large datasets. function processData(data: number[]) { // Implementation here... }

Perhaps a better approach to using TODO's would be opening issues.

Final Notes

Commenting code might seem straightforward, but there's an art to it. From my experience, the best comments are those that clarify the "why," add useful context, and are used thoughtfully.