Page cover

📃Meaningful Comments: The Art of Adding Value with Words

When it comes to code, clarity is king. While well-written code should be self-explanatory, sometimes a nudge in the right form of a comment can make all the difference. However, not all comments are created equal, and there's a fine line between enlightening and excessive.

Why Comment?

  1. Clarification: Even the cleanest code can have complex logic or algorithms that need some context. A well-placed comment can provide that insight.

  2. Documentation: For API developers or library creators, comments are often transformed into user-facing documentation.

  3. Intent: What is this code trying to achieve? While the 'what' is evident from the code, the 'why' often isn't.

  4. TODOs and FIXMEs: Pointing out where improvements can be made or bugs need addressing.

Characteristics of Meaningful Comments

  • Relevant: Only comment when necessary. Superfluous comments can clutter the code.

  • Concise: Get to the point quickly. A novel in the comments can be a distraction.

  • Timely: Comment while writing or refactoring. A fresh perspective ensures accuracy.

  • Maintainable: Outdated comments can mislead. Ensure they evolve with the code.

The Case Against Comments

  1. Self-documenting Code: The belief that clean, descriptive variable and function names can replace the need for comments.

  2. Maintenance Overhead: Comments can become outdated, leading to confusion.

  3. Redundancy: Comments that just restate the obvious can be deemed noise.

  4. Agile Practices: With continuous iteration, the code can change frequently, making comments a moving target.

Striking the Balance

  • Prioritise readability and understanding.

  • Value the time of the person who will eventually read or maintain the code (which might be future you!).

  • Respect the agreed-upon team practices and guidelines.

Examples of Meaningful Comments

1. Explaining Complex Logic

Without Comment:

function calculateDiscount(price, user) {
    return price * (1 - (user.memberSince / 100));
}

With Comment:

// Calculates a discount based on how long the user has been a member.
// For each year of membership, the user gets a 1% discount.
function calculateDiscount(price, user) {
    return price * (1 - (user.memberSince / 100));
}

Refactored with Naming Conventions:

function calculateMembershipBasedDiscount(price, user) {
    const annualDiscountPercentage = user.yearsAsMember / 100;
    return price * (1 - annualDiscountPercentage);
}

2. Describing Intent

Without Comment:

const threshold = 100;
if (user.points > threshold) {
    unlockFeature(user);
}

With Comment:

// Unlock a premium feature for users who've amassed more than a set threshold of points
const threshold = 100;
if (user.points > threshold) {
    unlockFeature(user);
}

Refactored with Naming Conventions:

const premiumFeaturePointsThreshold = 100;
if (user.points > premiumFeaturePointsThreshold) {
    unlockPremiumFeature(user);
}

TODOs and FIXMEs

function processPayment(user) {
    // TODO: Implement a fraud detection mechanism
    // FIXME: Payment sometimes fails with currency conversion issues
    return initiatePayment(user.cart);
}

Explaining a Workaround

Original:

def fetch_data():
    // Using a try-except block due to intermittent API failures.
    // This is a temporary solution until the API is stabilized.
    try:
        return api_request()
    except APIError:
        return backup_request()
}

Refactored with Naming Conventions:

def fetch_data_with_backup():
    try:
        return primary_api_request()
    except APIError:
        return backup_api_request()
}

Examples of Redundant or Bad Comments

Stating the Obvious

// Setting variable x to 10
let x = 10;

Outdated Comment

// Uses v1.0 of the API (Note: The API is now on v2.5)
fetchDataFromAPI();

Ambiguous Comment

// Fix this
calculateTax(income);

Takeaways

  • Aim for clarity in code first, then use comments to fill in the gaps.

  • Make each comment count; ensure it adds value.

  • Stay adaptive. The best approach is one that serves the team and the project's evolving needs.

Exercises & Examples

  1. Review a section of your code. Remove any redundant comments and add ones that clarify intent.

  2. In a team meeting, discuss the team's stance on comments. Can improvements be made in current practices?

Last updated