Why Code Comments Should Focus on Reasons Over Actions

Why Code Comments Should Focus on Reasons Over Actions

Introduction

Let’s get straight to the point: If your code is well-written, the functionality should be self-explanatory.

The what is clear from the code itself.

What isn’t always obvious is the why behind your approach — the reason for your decisions, the trade-offs you considered, and the reasoning that guided your implementation.

text

That's where comments should come in.

This article discusses the importance of writing meaningful code comments and their purpose.

The "What" Is in the Code, the "Why" Belongs in the Comments

If you’ve ever written a comment that describes what the code does, you’re not alone.

We’ve all done it—like "// Incrementing counter" or "// Set user ID".

But here's the thing: Comments should explain why you chose to do it that way as a developer.

Some Years Later…

Why Focusing on the 'Why' Changes Everything

1. Code Should Handle the "What"

When your code is clean and uses good variable names, the what is right there in front of me. What I need is the reason behind your choices.

Why did you use that obscure workaround? Why did you go for this less obvious solution?

Example: Instead of:

if (list.length === 0) // Check if list is empty
{
return;
}

A better comment might be:

if (list.length === 0) // Skip processing if the list is empty
{
return;
}

2. "Why" Comments Save Future You from Headaches

Be honest—six months from now, you probably won’t remember why you handled that strange edge case.

A solid comment explaining the choice will save you (and your teammates) a lot of time and frustration.

// Using a fallback method because library X has a known bug in version 2.3 
// that fails to handle empty arrays correctly.
function processData(data) {
    // If the data is empty, use the default value to avoid library X bug.
    const safeData = data.length === 0 ? getDefaultData() : data;

    // Proceed with processing using the library.
    libraryX.process(safeData);
}

The Downside of Commenting the 'What'

1. Redundant and Repetitive

If you’re writing comments like "// Add 1 to counter" right above counter++, you’re repeating yourself.

// Add 1 to counter
counter++

This is like narrating a movie scene with the same lines you hear from the actors. It’s pointless.

2. Misleading Comments Are Worse Than None

If you update the code but forget to update the comments, you end up with "// This only handles even numbers" when it actually covers odd numbers too.

// This function only handles even numbers.
function checkEven(num) {
    if (num % 2 === 0) {
        return "The number is even";
    } else {
        return "The number is odd";
    }
}

Now, the comment is not just useless—it’s dangerous.

How to Write Comments That Actually Help

1. Explain Your Intent, Not the Actions

Use comments to share the reasoning behind your decisions. Think of them as the backstory—why did you do it this way?

Example:

// Prioritize speed over memory efficiency because this needs to run in real-time.
function findLargest(arr) {
    let max = -Infinity;

    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    return max;
}

2. Highlight Edge Cases and Tricky Logic

If you had to do something clever or unusual, explain why. Don’t let future developers (or yourself) scratch their heads.

Example:

# Using a fixed timeout because of an API quirk; revisit when they release version 4.2.
def fetch_data_from_api(url):
    try:
        # Fixed timeout due to API's unreliability with dynamic timeout
        response = requests.get(url, timeout=10)
        return response.json()
    except TimeoutError:
        return None

3. Tie It to the Bigger Picture

Don’t just explain what’s happening—explain how it fits into the bigger plan. Give context.

Example:

// This section handles high-traffic scenarios; performance tweaks go here.
public void handleUserRequest(HttpServletRequest request) {
    // Caching data to reduce load on the database during peak hours
    String userData = cache.get(request.getUserID());
    if (userData == null) {
        userData = database.fetchUserData(request.getUserID());
        cache.put(request.getUserID(), userData);
    }
    process(userData);
}

When It's Okay to Comment the 'What'

Before you throw out all your "what" comments, remember there are exceptions. Complex algorithms and tricky implementations sometimes need a quick rundown. Just make sure you follow it up with a why.

# Using Dijkstra's algorithm for shortest path
# Chose this over Bellman-Ford for better performance with our sparse dataset.
def dijkstra(graph, start):
    shortest_paths = {vertex: float('infinity') for vertex in graph}
    shortest_paths[start] = 0
    priority_queue = [(0, start)]

    while priority_queue:
        current_distance, current_vertex = heapq.heappop(priority_queue)

        if current_distance > shortest_paths[current_vertex]:
            continue

        for neighbor, weight in graph[current_vertex].items():
            distance = current_distance + weight

            if distance < shortest_paths[neighbor]:
                shortest_paths[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))

    return shortest_paths

Good vs. Bad Comments: A Quick Comparison

Let’s put this into practice:

Bad Comment:

// Calculate total
let total = price * quantity;

This just restates the code.

Good Comment:

// Multiplies price by quantity for total cost;
// discounts are applied separately due to business requirements.
let total = price * quantity;

Now we understand why the discounts aren’t part of this calculation.

Below are some recommended resources 📚 to deepen your understanding of effective commenting and best practices for writing maintainable code:

Additional Resources

Best Practices for Writing Code Comments (Stack Overflow Blog)
A concise guide that emphasizes the importance of context over restating code in comments.

Best Practices for Writing Meaningful Code Comments: A Technical Guide (Medium)
Actionable tips on writing concise, meaningful comments that focus on explaining the why of code decisions.

Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
A foundational book on writing clean, maintainable code, which includes detailed guidance on when and how to use comments effectively.

Code Complete by Steve McConnell
A comprehensive resource on software construction, providing best practices for writing clear, maintainable code, including effective commenting techniques.

The Art of Readable Code by Dustin Boswell and Trevor Foucher
A guide to writing readable code, emphasizing the importance of simplicity, structure, and meaningful comments.

Writing Good Comments: Best Practices for Code (JetBrains)
JetBrains provides insights into writing clear, meaningful comments, avoiding redundant ones, and enhancing code quality.

Python Enhancement Proposals (PEP 8)
Python’s official style guide, which includes conventions for writing clear comments and documentation.

The Clean Coder: A Code of Conduct for Professional Programmers by Robert C. Martin
Discusses the discipline required for professional programming, including guidelines on comments and readability.

Effective Java by Joshua Bloch
A comprehensive guide for writing effective Java code, with advice on when and how to use comments effectively.

The Pragmatic Programmer: Your Journey to Mastery by Andrew Hunt and David Thomas
Offers advice on improving coding practices, including guidance on writing clean, understandable comments.

The Software Craftsman: Professionalism, Pragmatism, Pride by Sandro Mancuso
A guide for becoming a better software developer, with an emphasis on professionalism, clean code, and effective commenting.

These resources are essential for developing a professional and thoughtful approach to commenting that enhances code readability and maintainability.

🔔 If you need any help, feel free to reach out:

Preston Mayieka's LinkedIn

https://x.com/preston_mayieka

Final Thoughts

Comments should always add value, not create unnecessary clutter. If they don't provide meaningful context, they risk becoming noise that detracts from the code's readability.

Rather than explaining what the code does (which is already apparent from the code itself), focus on explaining why certain decisions were made.

This approach helps future developers—and your future self—understand the reasoning behind your choices.

Remember, code is read far more often than it's written, so make the reading experience as enjoyable and insightful as possible.