Self-Documenting Code vs Comments
What you'll learn: How to balance writing clear, readable code with using comments effectively for truly complex scenarios.
The Core Idea
Self-documenting code uses clear names, simple structure, and obvious logic so that anyone reading it understands what it does without needing extra explanation. Comments explain why something exists or how a complex algorithm works when the code alone can't make it obvious.
Think of it like furniture assembly instructions: good design means the pieces fit together obviously (self-documenting), but you still need warnings like "Don't overtighten bolt C—it will crack the frame" (comments for non-obvious details).
When Code Should Speak for Itself
Use intention-revealing names and simple structure first:
# BAD: Needs comment to explain
def calc(x, y): # Calculate employee overtime pay
return x * 1.5 * y
# GOOD: Self-documenting
def calculate_overtime_pay(hours_worked, hourly_rate):
OVERTIME_MULTIPLIER = 1.5
return hours_worked * OVERTIME_MULTIPLIER * hourly_rate
The second version doesn't need a comment—the names tell the story.
When Comments Add Value
Write comments for:
- Why decisions were made: "Using bubble sort here because dataset is always < 10 items"
- Complex algorithms: "Implementing Dijkstra's algorithm for shortest path"
- Non-obvious constraints: "API returns null on Sundays—legacy behavior we can't change"
- Legal or regulatory requirements: "Retention period mandated by GDPR Article 17"
Avoid comments that just repeat what the code already says clearly.
The Balance
Start by making your code as clear as possible through naming and structure. Only add comments when the intent or reasoning isn't obvious from the code itself. Your code tells the "what" and "how," while comments explain the "why" and "context."
Key Takeaway: Write code so clear it rarely needs comments, then use comments strategically to explain why and document complexity that can't be simplified away.