We’ve all been there. You’re staring at a function you wrote three months ago, and you have absolutely no idea why you made that particular design choice. Or worse, you’re debugging someone else’s “clever” code with zero documentation.
Enter Claude—your AI pair programmer that doesn’t just write code, but writes the kind of comments that actually save time. Here are the 10 types of comments that experienced developers wish they’d written (but Claude generates automatically).
1. TODO with Context: The Actionable Reminder
The Problem: Most TODO comments are useless.
javascript
// TODO: fix this
Thanks for nothing, past-me.
The Claude Way:
javascript
// TODO: Add rate limiting here - API allows 100 req/min per IP
// Consider token bucket algorithm (libraries: bottleneck, limiter)
// Estimated effort: 2-3 hours
async function handleAPIRequest(req, res) {
const data = await fetchFromExternalAPI(req.body);
return res.json(data);
}
Why It Works: Claude provides context, suggests solutions, and even estimates effort. When you come back to this TODO, you won’t waste 30 minutes re-researching the problem.
2. Why Not What: The Decision Rationale
The Problem: Code tells you what it does. It doesn’t tell you why you chose that approach.
javascript
const debouncedSearch = debounce(handleSearch, 300);
The Claude Way:
javascript
// Using debounce instead of throttle because we care about the final
// search term, not intermediate keystrokes. 300ms balances responsiveness
// with API cost (avg user types at ~250ms per character).
const debouncedSearch = debounce(handleSearch, 300);
Why It Works: Six months from now, someone won’t refactor this to throttle and accidentally break the UX. Claude explains the reasoning, preventing well-intentioned mistakes.
3. Edge Case Documentation: The Bug Preventer
The Problem: Edge cases are where bugs hide, and they’re the first thing forgotten.
python
def process_results(items):
if not items:
return None
return [format_item(item) for item in items]
The Claude Way:
python
def process_results(items):
# Edge case: Returns None (not []) for empty input to match
# legacy API behavior. Client code expects null checks.
# See: https://github.com/company/legacy-api/issues/892
#
# Breaking this will fail silently in production because mobile
# app v2.1-2.3 crashes on empty arrays in this context.
if not items:
return None
return [format_item(item) for item in items]
Why It Works: Claude documents the “why” behind quirky behavior, preventing the “obvious bug fix” that breaks production. The GitHub link is chef’s kiss.
4. Performance Notes: The Optimization Guide
The Problem: You write an O(n²) algorithm knowing it’s fine for your use case, but six months later someone “optimizes” it unnecessarily.
javascript
function findDuplicates(users) {
const duplicates = [];
for (let i = 0; i < users.length; i++) {
for (let j = i + 1; j < users.length; j++) {
if (users[i].email === users[j].email) {
duplicates.push(users[i]);
}
}
}
return duplicates;
}
The Claude Way:
javascript
function findDuplicates(users) {
// Performance: O(n²) complexity is acceptable here
// - Max users per organization: 50 (enforced by plan limits)
// - Runs once during account setup, not in hot path
// - Hash map approach adds complexity without benefit at this scale
//
// OPTIMIZE IF: We support enterprise plans with 500+ users
const duplicates = [];
for (let i = 0; i < users.length; i++) {
for (let j = i + 1; j < users.length; j++) {
if (users[i].email === users[j].email) {
duplicates.push(users[i]);
}
}
}
return duplicates;
}
Why It Works: Claude sets clear boundaries for when optimization matters. The “OPTIMIZE IF” trigger prevents premature optimization while flagging when things change.
5. API Gotchas: The Third-Party Trap Detector
The Problem: External APIs have undocumented quirks that bite you in production.
javascript
app.post('/webhook/stripe', async (req, res) => {
const event = stripe.webhooks.constructEvent(
req.body,
req.headers['stripe-signature'],
process.env.STRIPE_WEBHOOK_SECRET
);
await processPayment(event);
res.json({ received: true });
});
The Claude Way:
javascript
app.post('/webhook/stripe', async (req, res) => {
// CRITICAL: Stripe webhook signatures MUST be verified within 5 minutes
// of generation or they fail silently. This can happen if:
// - Server time is off by >5 min (check NTP sync)
// - Request queued too long (monitor queue depth)
// - Clock skew between Stripe and your servers
//
// Symptoms: Webhooks work in test mode, fail in production randomly
// Debug: Check stripe.webhooks.signature.verify logs for timestamp errors
const event = stripe.webhooks.constructEvent(
req.body,
req.headers['stripe-signature'],
process.env.STRIPE_WEBHOOK_SECRET
);
await processPayment(event);
res.json({ received: true });
});
Why It Works: Claude documents the gotcha that isn’t in the official docs but is all over Stack Overflow. When this breaks at 2 AM, you’ll know exactly where to look.
6. Temporary Workarounds: The Technical Debt Tracker
The Problem: Hacks live forever because no one remembers they’re hacks.
javascript
setTimeout(() => {
img.onload = handleImageLoad;
}, 0);
The Claude Way:
javascript
// HACK: setTimeout workaround for Safari 15 cached image bug
//
// Problem: Safari doesn't fire onload for cached images
// Impact: Image galleries don't render on repeat visits
// Proper fix: Use img.complete check + immediate callback
//
// TODO: Remove this when Safari 15 usage drops below 2%
// Current stats: https://analytics.company.com/browser-stats
// Blocked by: Mobile users slow to upgrade
// Created: 2024-01-15 by @alice
setTimeout(() => {
img.onload = handleImageLoad;
}, 0);
Why It Works: Claude turns “weird code” into documented technical debt with a clear removal plan. The analytics link makes the TODO actionable.
7. Configuration Context: The Magic Number Decoder
The Problem: Magic numbers everywhere, no one knows why.
python
@retry(max_attempts=3, backoff=exponential)
def fetch_data(url):
return requests.get(url, timeout=5)
The Claude Way:
python
# Retry configuration tuned for external API characteristics:
# - 3 attempts: Balances reliability (95% success rate after 3 tries)
# vs user patience (max wait ~7 seconds)
# - Exponential backoff: 1s, 2s, 4s delays
# - Prevents thundering herd on API recovery
# - Gives temporary network issues time to resolve
# - 5s timeout: API p99 latency is 3.2s, 5s catches stragglers
#
# These values were A/B tested in Q4 2024 - see experiment results:
# https://wiki.company.com/experiments/api-retry-optimization
@retry(max_attempts=3, backoff=exponential)
def fetch_data(url):
return requests.get(url, timeout=5)
Why It Works: Claude explains the math and links to the data. Future developers won’t “tune” these values and accidentally tank your reliability metrics.
8. Cross-Reference Comments: The Sync Reminder
The Problem: Duplicated logic drifts apart because developers don’t know it’s duplicated.
typescript
// Validation logic
const isValidEmail = (email: string) => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};
The Claude Way:
typescript
// Email validation logic - KEEP IN SYNC with:
// - Backend: UserSchema.ts line 45 (database validation)
// - Mobile: ValidationUtils.swift line 112 (client-side check)
// - Onboarding: SignupForm.tsx line 89 (UX validation)
//
// Last synced: 2024-12-01
// Next review: When adding new TLDs or updating RFC compliance
//
// Note: This is intentionally duplicated (not DRY) because each
// layer needs to fail gracefully with different error messages
const isValidEmail = (email: string) => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};
Why It Works: Claude maps the duplication explicitly and justifies why it exists. Developers can make informed decisions about whether to refactor or keep in sync.
9. Assumption Documentation: The Precondition Enforcer
The Problem: Functions have hidden preconditions that cause mysterious bugs.
javascript
function chargeCustomer(amount, customerId) {
return stripe.charges.create({
amount: amount,
customer: customerId,
currency: 'usd'
});
}
The Claude Way:
javascript
// PRECONDITIONS (violations will fail in production):
// 1. Input MUST be sanitized - this function does NOT validate
// (validation happens in PaymentMiddleware.ts)
// 2. Amount must be in CENTS (not dollars) - stripe expects integer cents
// 3. Customer ID must exist in Stripe (no validation to avoid extra API call)
//
// UNSAFE: Do NOT call directly from API routes
// SAFE: Only call after paymentMiddleware.validate()
//
// Why: This function is in the hot path for checkout - we trade
// safety for performance by validating once upstream
function chargeCustomer(amount, customerId) {
return stripe.charges.create({
amount: amount,
customer: customerId,
currency: 'usd'
});
}
Why It Works: Claude makes invisible contracts visible. The ALL-CAPS “UNSAFE” warning prevents the bug before it happens.
10. Future-Proofing Notes: The Maintenance Roadmap
The Problem: You add a feature and break three related things because you didn’t know they existed.
javascript
const PAYMENT_METHODS = {
CARD: 'card',
BANK: 'bank_account'
};
The Claude Way:
javascript
// Payment method constants - used across checkout flow
//
// WHEN ADDING NEW PAYMENT METHODS, you must also update:
// 1. Frontend:
// - PaymentIcon.tsx (add icon for new method)
// - CheckoutForm.tsx (add form fields if needed)
// - PaymentMethodSelector.tsx (add to dropdown)
// 2. Backend:
// - payment-processor.ts (add processing logic)
// - webhooks/payment-updated.ts (handle status changes)
// 3. Tests:
// - checkout-flow.test.ts (add E2E test scenario)
// - payment-processor.test.ts (unit tests)
// 4. Analytics:
// - events.ts (add 'payment_method_selected' event variant)
// - Mixpanel dashboard (create conversion funnel)
// 5. Documentation:
// - API docs at docs/api/payments.md
// - Support team runbook at wiki/payment-troubleshooting
//
// Example PR for reference: https://github.com/company/app/pull/1247
const PAYMENT_METHODS = {
CARD: 'card',
BANK: 'bank_account'
};
Why It Works: Claude creates a checklist that prevents incomplete features. The example PR is gold for onboarding new developers.
The Real Impact: Time Saved
Let’s do the math:
- Average time saved per well-documented code section: 15-30 minutes
- Number of times you revisit old code per week: 10-20 times
- Time saved per week: 2.5-10 hours
- Time saved per year: 130-520 hours (3-13 weeks!)
That’s not counting:
- Bugs prevented by edge case documentation
- Onboarding time reduced (new devs understand code faster)
- Code review time saved (reviewers understand intent immediately)
- Technical debt managed (temporary hacks don’t become permanent)
How to Use Claude for Better Comments
Here’s my workflow:
- After writing code: Ask Claude to “review this function and add comprehensive comments explaining the why, edge cases, and future considerations”
- Before committing: Ask Claude to “identify any magic numbers, assumptions, or gotchas that should be documented”
- During code review: Ask Claude to “explain this code to a junior developer” – if the explanation requires lots of clarification, you need better comments
- For legacy code: Ask Claude to “analyze this function and document its behavior, edge cases, and any potential issues”
The Bottom Line
Good comments aren’t about explaining what code does—your code should already do that. Good comments explain:
- Why decisions were made
- What edge cases exist
- When to optimize or refactor
- Where related code lives
- How to avoid common pitfalls
Claude excels at generating these context-rich comments because it thinks about code the way experienced developers do—considering edge cases, performance implications, and maintenance burden.
Want more AI tools, breakdowns, and no-fluff recommendations?
Follow ToolTechSavvy
https://tooltechsavvy.com/



