styleguide

Commenting Practices

Effective commenting is an essential practice in software development to ensure code clarity, maintainability, and collaboration among developers. This document outlines rules and best practices for writing comments in codebases.

1. General Guidelines


2. Types of Comments

2.1. Single-Line Comments

// Check if the user is authenticated
if (!user.isAuthenticated) redirectToLogin();

2.2. Multi-Line Comments

/*
 * This function calculates the factorial of a number.
 * It uses a recursive approach to multiply all positive integers up to the given number.
 */
function factorial(n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

2.3. Documentation Comments

/**
 * Calculates the sum of two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @return {number} The sum of the two numbers.
 */
function add(a, b) {
    return a + b;
}

3. Writing Effective Comments

3.1. Explain Complex Logic

# Use binary search to improve performance on sorted data
while left <= right:
    mid = (left + right) // 2
    if data[mid] == target:
        return mid

3.2. Highlight Important Decisions

// Using a LinkedHashMap to maintain insertion order for predictable iteration
Map<String, String> map = new LinkedHashMap<>();

3.3. Warn About Side Effects or Limitations

// This function assumes $array is sorted; behavior is undefined otherwise.
function binarySearch($array, $key) {
    // ... implementation ...
}

4. Avoiding Common Mistakes

4.1. Avoid Redundant Comments

// BAD: Adds two numbers
int sum = a + b;

// GOOD: Add numbers to calculate the total expense
int totalExpense = foodCost + transportCost;

4.2. Avoid Hard-Coding Comments

# BAD: Set the timeout to 5000ms
config.timeout = 5000;

# GOOD: Set the timeout for the network request
config.timeout = NETWORK_TIMEOUT;

5. Tools and Conventions


6. Commenting for Collaboration

// TODO: Implement error handling for API requests
fetchData();

// FIXME: Resolve memory leak issue in the caching mechanism
cache.clear();