Art of CommentingTopic 3 of 4~5 min

Comment Style Guidelines

Area Developer's Comments Longer Than Code; Colleagues Stage Intervention

Museum of commenting styles

Dear Marilyn: How much commenting is too much? My colleague writes a paragraph for every line of code. I write nothing. Surely there's a middle ground?

— Seeking Balance in San Francisco

Dear Seeking: The golden rule is this: comments should not exceed the length of the code they explain by too much. If they do, it's a sign the code itself is too complicated and should be refactored.

The Good, The Bad, and The Ugly

Good: Explains the "Why"

// Retry up to 3 times because the API 
// occasionally returns 503 during deployments
for (int i = 0; i < 3; i++) {
    var result = await api.Call();
    if (result.Success) break;
    await Task.Delay(1000);
}

Bad: States the Obvious

// Increment i by 1
i++;

// Check if user is null
if (user == null) {
    // Return null
    return null;
}

These comments add no value. The code already says exactly what they say.

Ugly: Lies

// Calculate the user's age
var discount = price * 0.15;

A wrong comment is worse than no comment. When code changes, update the comments!

Comment Formatting Best Practices

PracticeExampleWhy
Use complete sentences// This validates the input format.Clarity and professionalism
Start with capital letter// Calculate tax after discountConsistency and readability
Match indentation // Comment at same level as codeVisual association with code
Keep line length reasonable// Max ~80 characters per lineReadability without scrolling
Update when code changes// [Updated 2024-03-22]Prevent misleading information

Quick Check

Which of these comments provides the most value?