| name | code-documentation |
| description | Guidelines for self-explanatory code and meaningful documentation. Activate when working with comments, docstrings, documentation, code clarity, API documentation, JSDoc, or discussing code commenting strategies. Guides on why over what, anti-patterns, decision frameworks, and language-specific examples. |
Code Documentation & Self-Explanatory Code
Auto-activate when: User discusses comments, documentation, docstrings, code clarity, code quality, API docs, JSDoc, Python docstrings, or asks about commenting strategies.
Core Principle
Write code that speaks for itself. Comment only when necessary to explain WHY, not WHAT.
Most code does not need comments. Well-written code with clear naming and structure is self-documenting.
The best comment is the one you don't need to write because the code is already obvious.
The Commenting Philosophy
When to Comment
✅ DO comment when explaining:
- WHY something is done (business logic, design decisions)
- Complex algorithms and their reasoning
- Non-obvious trade-offs or constraints
- Workarounds for bugs or limitations
- API contracts and public interfaces
- Regex patterns and what they match
- Performance considerations or optimizations
- Constants and magic numbers
- Gotchas or surprising behaviors
❌ DON'T comment when:
- The code is obvious and self-explanatory
- The comment repeats the code (redundant)
- Better naming would eliminate the need
- The comment would become outdated quickly
- It's decorative or organizational noise
- It states what a standard language construct does
Comment Anti-Patterns
❌ 1. Obvious Comments
BAD:
counter = 0
counter += 1
user_name = input("Enter name: ")
Better: No comment needed - the code is self-explanatory.
❌ 2. Redundant Comments
BAD:
def get_user_name(user):
return user.name
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total
Better:
def get_user_name(user):
return user.name
def calculate_total(items):
return sum(item.price for item in items)
❌ 3. Outdated Comments
BAD:
tax = price * 0.08
def old_function():
pass
Better: Keep comments in sync with code, or remove them entirely.
❌ 4. Noise Comments
BAD:
def calculate():
result = 0
return result
Better: Remove all of these comments.
❌ 5. Dead Code & Changelog Comments
BAD:
Better: Delete the code. Git has the history.
Good Comment Examples
✅ Complex Business Logic
def calculate_progressive_tax(income):
if income <= 10000:
return income * 0.10
else:
return 1000 + (income - 10000) * 0.20
✅ Non-obvious Algorithms
for k in range(vertices):
for i in range(vertices):
for j in range(vertices):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
✅ Regex Patterns
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
✅ API Constraints or Gotchas
await rate_limiter.wait()
response = await fetch(github_api_url)
✅ Workarounds for Bugs
if library_version == "2.1.0":
apply_workaround()
Decision Framework
Before writing a comment, ask yourself:
Step 1: Is the code self-explanatory?
- If YES → No comment needed
- If NO → Continue to step 2
Step 2: Would a better variable/function name eliminate the need?
- If YES → Refactor the code instead
- If NO → Continue to step 3
Step 3: Does this explain WHY, not WHAT?
- If explaining WHAT → Refactor code to be clearer
- If explaining WHY → Good comment candidate
Step 4: Will this help future maintainers?
- If YES → Write the comment
- If NO → Skip it
Special Cases for Comments
Public APIs and Docstrings
Python Docstrings
def calculate_compound_interest(
principal: float,
rate: float,
time: int,
compound_frequency: int = 1
) -> float:
"""
Calculate compound interest using the standard formula.
Args:
principal: Initial amount invested
rate: Annual interest rate as decimal (e.g., 0.05 for 5%)
time: Time period in years
compound_frequency: Times per year interest compounds (default: 1)
Returns:
Final amount after compound interest
Raises:
ValueError: If any parameter is negative
Example:
>>> calculate_compound_interest(1000, 0.05, 10)
1628.89
"""
if principal < 0 or rate < 0 or time < 0:
raise ValueError("Parameters must be non-negative")
return principal * (1 + rate / compound_frequency) ** (compound_frequency * time)
JavaScript/TypeScript JSDoc
async function fetchUser(userId, options = {}) {
}
Constants and Configuration
MAX_RETRIES = 3
API_TIMEOUT = 10000
CACHE_TTL = 300
Annotations for TODOs and Warnings
def temporary_auth(user):
return True
def sort_in_place(arr):
arr.sort()
return arr
def get_connection():
return create_connection()
def expensive_calculation(data):
return complex_algorithm(data)
def build_query(user_input):
sanitized = escape_sql(user_input)
return f"SELECT * FROM users WHERE name = '{sanitized}'"
Common Annotation Keywords
TODO: - Work that needs to be done
FIXME: - Known bugs that need fixing
HACK: - Temporary workarounds
NOTE: - Important information or context
WARNING: - Critical information about usage
PERF: - Performance considerations
SECURITY: - Security-related notes
BUG: - Known bug documentation
REFACTOR: - Code that needs refactoring
DEPRECATED: - Soon-to-be-removed code
Refactoring Over Commenting
Instead of Commenting Complex Code...
BAD: Complex code with comment
if user.role == "admin" or (user.permissions and "special" in user.permissions):
grant_access()
...Extract to Named Function
GOOD: Self-explanatory through naming
def user_has_admin_access(user):
return user.role == "admin" or has_special_permission(user)
def has_special_permission(user):
return user.permissions and "special" in user.permissions
if user_has_admin_access(user):
grant_access()
Language-Specific Examples
JavaScript
const debouncedSearch = debounce(searchAPI, 500);
let count = 0;
count++;
const seen = new Set(ids);
Python
index = bisect.bisect_left(sorted_list, target)
def get_total(items):
return sum(items)
def validate_user(user):
if not user or not user.id:
raise ValueError("Invalid user")
return user
TypeScript
const element = document.getElementById('app') as HTMLElement;
const sum = a + b;
const newConfig = { ...config };
Comment Quality Checklist
Before committing, ensure your comments:
Summary
Priority order:
- Clear code - Self-explanatory through naming and structure
- Good comments - Explain WHY when necessary
- Documentation - API docs, docstrings for public interfaces
- No comments - Better than bad comments that lie or clutter
Remember: Comments are a failure to make the code self-explanatory. Use them sparingly and wisely.
Key Takeaways
| Goal | Approach |
|---|
| Reduce comments | Improve naming, extract functions, simplify logic |
| Improve clarity | Use self-explanatory code structure, clear variable names |
| Document APIs | Use docstrings/JSDoc for public interfaces |
| Explain WHY | Comment only business logic, algorithms, workarounds |
| Maintain accuracy | Update comments when code changes, or remove them |