Chain of Thought Comments
Help AI understand WHY code exists, not just what it does.
What are Chain of Thought Comments?
Chain of Thought (CoT) comments document the reasoning behind code decisions. They help both humans and AI understand:
- →Why this approach was chosen over alternatives
- →What problem this code solves
- →What constraints influenced the design
- →What would break if this code changed
Why AI Needs Context
Without reasoning context, AI might "improve" code in ways that break things:
Without CoT
// Fetch users
function getUsers() {
return db.query('SELECT * FROM users LIMIT 100');
}AI might remove the LIMIT: "Why limit to 100? Let's get all users."
With CoT
/**
* REASONING: Limited to 100 because:
* 1. UI can't render 10k+ users performantly
* 2. Full table scan would timeout
* 3. Pagination handled by separate endpoint
*/
function getUsers() {
return db.query('SELECT * FROM users LIMIT 100');
}AI understands the limit is intentional and won't remove it.
CoT Comment Format
Use structured comments that AI can easily parse:
/**
* DESIGN DECISION: Using setTimeout instead of setInterval
*
* REASONING:
* 1. setInterval can stack calls if handler takes too long
* 2. setTimeout guarantees gap between executions
* 3. Easier to cancel and restart with dynamic delays
*
* ALTERNATIVES CONSIDERED:
* - setInterval: Rejected due to stacking issue
* - requestAnimationFrame: Overkill for this use case
*
* CONSTRAINTS:
* - Must handle network latency (up to 5s)
* - Must not block UI thread
*
* PATTERN: Pattern-POLLING-001
*/
function pollForUpdates() {
fetchUpdates().then(() => {
setTimeout(pollForUpdates, 5000);
});
}Key Sections
- DESIGN DECISION: One-line summary of the choice
- REASONING: Numbered list of why this approach
- ALTERNATIVES CONSIDERED: What else was tried
- CONSTRAINTS: What limitations influenced design
- PATTERN: Reference to a documented pattern (optional)
When to Add CoT Comments
✓ Non-obvious code
Code that looks wrong but is actually correct (workarounds, edge cases)
✓ Performance-critical sections
Optimizations that might look like premature optimization
✓ Business logic
Rules that come from requirements, not technical necessity
✓ Tricky algorithms
Complex logic that AI might try to "simplify"
How AI Uses CoT Comments
When AI assistants like Claude Code or Cursor read your code, they automatically see and understand CoT comments:
- 1AI reads the file you're working on, including comments
- 2CoT comments provide context about design decisions
- 3AI understands constraints and avoids breaking documented patterns
- 4AI respects the reasoning and suggests compatible changes
Tips for Effective CoT
- 1.Be specific - "Performance" is vague; "Reduces queries from 100 to 1" is clear
- 2.Explain the "why" - The code shows "what"; comments explain "why"
- 3.Include constraints - What can't change and why
- 4.Reference tickets/docs - Link to requirements or bug reports
- 5.Keep it current - Update CoT when reasoning changes