
Writing Code Comments
FreeEnhance code clarity by writing meaningful comments.
Free · Opens the source repo
What Writing Code Comments does
The Writing Code Comments skill provides a structured approach to commenting in code, emphasizing the importance of clarity and relevance. It encourages developers to critically assess the necessity of each comment, ensuring that only those which provide essential context or reasoning are retained. By focusing on the 'why' rather than the 'what', this skill helps maintain a clean and understandable codebase, making it easier for future developers to navigate and comprehend the logic behind the code.
To effectively use this skill, developers should ask themselves a pivotal question before adding or editing any comment: 'What does this tell a future reader that the code itself doesn't?' If the comment merely restates the code's functionality, it should be removed. Instead, comments should clarify non-obvious reasons for certain decisions, warn about potential consequences, or point to external context that might not be readily apparent from the code alone. This approach not only improves the quality of comments but also encourages better coding practices, such as using descriptive variable names and breaking down complex functions.
The skill also outlines specific types of comments to avoid, such as those that narrate the code, document change history, or include perishable measurements. By eliminating these cluttering elements, developers can focus on writing comments that add true value. The guidance provided is applicable across various programming languages, including Python, TypeScript, Go, Rust, and SQL, making it a versatile tool for any developer looking to enhance their code documentation practices.
In summary, the Writing Code Comments skill is designed for developers who want to improve their commenting practices, reduce noise in their codebases, and ensure that comments serve a clear purpose. By adopting this skill, teams can foster better communication and understanding within their code, ultimately leading to more maintainable and efficient software development.
When to use it
Use this skill when writing or reviewing code comments to ensure clarity and relevance.
When not to use it
This skill is not suitable for user-facing copy or commit messages, as it focuses solely on code comments.
What you can build with it
Code Review Process
Incorporate this skill during code reviews to ensure that comments are meaningful and necessary, enhancing the overall quality of the codebase.
Refactoring Existing Code
Use this skill when refactoring to evaluate and improve existing comments, ensuring they provide valuable insights into the code's logic.
Onboarding New Developers
Leverage this skill to help onboard new team members by teaching them how to write effective comments that clarify code intent and structure.
How to install Writing Code Comments
View source1. Install with the skills CLI
npx skills add posthog/posthog/writing-code-comments --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by posthogWriting code comments
Run this before adding or editing any comment. The default is no comment. Good code with clear names carries most of its meaning on its own; a comment earns its place only when it tells a reader something the code cannot.
The gate: one question
Before writing a comment, answer:
What does this tell a future reader that the code itself doesn't?
If the answer is "it restates what the code does", delete it. Rename the variable or extract a function instead.
A comment worth keeping answers a why the code can't:
- ✅
# ATOMIC_REQUESTS is off, so wrap the two writes that must commit together - ✅
// Stripe sends the amount in cents; the rest of our system uses dollars - ✅
# Kept in sync with the enum in migrations/0042; update both
Delete these
Narration that restates the code
- ❌
# increment the counterabovecounter += 1 - ❌
// loop over usersabovefor user of users - ❌
# return the resultabovereturn result
If a block needs narration to be followed, the fix is smaller functions and better names, not a comment.
Change history and chat context
Never record how the code got here. That belongs in the commit message and PR description, where it's attached to the diff and searchable. In the source it's noise that goes stale immediately.
- ❌
# previously used a set here, switched to a list for ordering - ❌
// per PR #1234/# as discussed/# changed because the old way broke - ❌
# AI: generated this helper/// agent: refactored - ❌
# TODO(2024-01): remove after migrationleft in long after the migration
Perishable measurements and current-state stamps
Measured timings, counts, and rates rot silently: nothing forces them to update, and a rotted number misleads the next person sizing a timeout or shard count. The same goes for "currently" / "today" hedges, because the sentence states the same fact without them. State the durable relationship the number stood for.
- ❌
# skip the ~20 min buildwhen the durable fact is that the build is expensive - ❌
# ci-backend runs ~28m, so 60m ≈ one red resultinstead of "sized past a full run of the slowest workflow" - ❌
# no story currently opts into webkit snapshotswhere dropping "currently" states the same fact - ❌
# ~20 minutes in June, past 25 by Julybecause trend narration is change history
Numbers that stay:
- A dated snapshot:
# as of August 2024, Homebrew ships 4.13.2(the date makes staleness visible) - A restated adjacent code literal:
# runs that took >5 min (300 seconds)beside the300(it updates with the code) - A platform constant:
# GitHub's comment size limit (~64KB) - A target or budget:
# Target: ~15 min per shard(policy, not measurement) - Cited evidence:
# 30% peak memory observed on 16-core runs (#46853)(the link dates it)
Commented-out code
Delete it; the version history has it if it's needed again. Commented-out code is ambiguous to the next reader, who can't tell whether it's a note, a rollback plan, or an accident.
Redundant docstrings and type restatements
- ❌ A docstring that repeats the function name in prose:
"""Gets the user by id."""onget_user_by_id - ❌
# type: stringon an already-typed field - ❌ Python test doc comments (the repo convention is none; the test name says it)
Keep these
- A why that isn't obvious from the code: a workaround, a performance trade-off, a spec quirk, an ordering constraint.
- A warning about a consequence that lives elsewhere: "changing this breaks the cache key", "callers rely on this being sorted".
- A pointer to context a reader can't reconstruct from the repo: a link to the spec, ticket, or the reason a surprising value was chosen.
Style
Write comments the way you'd write technical documentation: explicit and precise. State the reasoning so the reader does not have to infer it. Length is not a target in either direction: don't clip a comment to look terse, and don't pad it to look thorough. Say what needs saying and stop.
- Be explicit and technical. State the cause and effect. Name the actual conditions, values, and consequences. A reader should not have to reconstruct your reasoning from a hint.
- Let length follow the content. One line is fine when one line covers it; use more when the reasoning needs more. Neither brevity nor length is the goal.
- No em-dash. The tell to avoid is the clipped two-part phrase joined by a dash, like
# do the thing — it's faster. Use a real connective instead ("because", "so that", "which means", "to avoid"). - Explain why, not what. The what is in the code; the why usually is not.
- Preserve existing comments when moving or refactoring code, unless the change makes them wrong. Don't drop an existing why just because you're relocating the function.
- Match the surrounding density. Don't add a comment to every line of a file that had none; don't strip a well-commented module bare.
The fix for the em-dash is the connective, not more words. A short comment is fine once the dash is gone:
- ❌
# batch here — avoids N+1 - ✅
# batch here to avoid an N+1 against posthog_organizationmembership
When you're tempted to comment
Try, in order: (1) a better name, (2) a smaller function, (3) a type. Reach for a comment only when none of those can carry the meaning.
Frequently asked questions about Writing Code Comments
Similar skills
Markdown to HTML Conversion
Efficiently convert Markdown documents to HTML.
Code Tour
Create structured walkthroughs for codebases.
Acquire Codebase Knowledge
Streamline onboarding with comprehensive codebase documentation.
Documentation & Modernization
Streamline codebase documentation and modernization planning.
Azure Resource Visualizer
Generate architecture diagrams for Azure resources.
CLAUDE.md Improver
Optimize your CLAUDE.md files for better project context.
