Course contentsShow
← Software Engineering
Lesson 374 of 1,93311. Code Quality and ReadabilityFree lesson

When to Write Comments

Learn when comments add value versus when they're redundant, focusing on explaining 'why' over 'what' the code does.

When to Write Comments

You'll learn when comments genuinely help—and when they just add noise to your code.

The Core Principle: Explain Why, Not What

Comments should reveal why you made a decision, not parrot what the code obviously does. Well-named variables and functions already show what's happening—but they can't capture the reasoning behind non-obvious choices.

Bad comment (redundant):

# Increment counter by 1
counter = counter + 1

The code already says this clearly.

Good comment (explains why):

# Use exponential backoff because the API rate-limits after 3 rapid requests
wait_time = base_delay * (2 ** retry_count)

Now we understand the reasoning—why exponential backoff instead of a fixed delay.

When Comments Add Value

  • Business rules or constraints: "VAT calculation uses 19% per EU Directive 2006/112/EC"
  • Non-obvious algorithms: "Using Floyd's cycle detection to find duplicates in O(1) space"
  • Workarounds: "Setting timeout to 5000ms because third-party service sometimes stalls"
  • TODO or FIXME markers: "TODO: Replace with async API call in next sprint"

When Comments Are Redundant

  • The code is self-explanatory through good naming
  • You're describing what a clearly-written function does
  • You're compensating for poor code structure (refactor instead!)

Think of comments like highway signs: you don't need one every meter telling you you're driving forward. You need them at exits, hazards, and decision points.

Key Takeaway: Write comments that explain why decisions were made, not what well-written code already communicates. If you're tempted to comment what, improve the code's clarity instead.