关于 code-comments
code-comments 是面向开发者和编码 Agent 的代码注释写作指南,强调先通过代码表达意图,再用简短、贴近代码的注释说明无法从实现中看出的原因、约束和不变量。
主要功能
- 01优先重构代码表达意图
- 02注释说明原因、约束与不变量
- 03保持注释简短并贴近代码
- 04提供决策与兼容性注释模板
- 05涵盖文档注释及审查清单
适用场景
- 01为非显而易见的实现补充背景
- 02记录必须维持的代码不变量
- 03解释兼容性限制或历史决策
- 04审查并清理过时或冗余注释
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ caidanw/ skills --skill code-comments安装后在 Claude Code 中输入/code-comments确认已加载。
详细介绍
代码注释
编写代码时,让代码结构说明「是什么」。编写注释时,让未来的人类和 Agent 理解「为什么」「为什么不」「必须保持什么不变」以及「这里已经发生过什么」。
核心规则
按以下顺序处理:
1. Rename, extract, reorder, or delete code until the intent is obvious
2. Add a comment only when the missing context cannot live in code
3. Put the shortest useful comment as close as possible to the code
4. Keep the comment short, local, and durable
好的注释能减少错误修改。出色的注释能阻止人类和 Agent 重蹈覆辙。
注释检验
编写注释前,先问自己:
Can clearer code remove the need for this comment?
Yes -> refactor first
No -> comment the missing context
Will this comment still be true after a small refactor?
No -> move the detail into code or delete it
Yes -> keep it
Does this comment tell the reader something the code cannot?
No -> delete it
Yes -> keep it
应该注释什么
注释只有在记录以下内容之一时才有价值:
意图
这段代码为何存在。
// Normalize partner payloads here so the rest of the pipeline can assume
// internal field names and avoid partner-specific branches.
约束
由于产品、法律、协议或平台限制,代码必须遵守的规则。
// Keep card brand names verbatim for PCI audit exports.
// Product copy uses friendly labels elsewhere, but not in this file.
不变量
未来修改时也必须保持成立的属性。
// INVARIANT: cache keys must include tenantId.
// Cross-tenant collisions become data leaks, not cache misses.
权衡
为什么不那么显而易见的实现方式胜过看起来更简单的方案。
// We batch writes every 250ms to cut lock contention.
// Immediate writes looked simpler but doubled p95 latency in production.
历史
未来编辑者应该了解的已发生事项。
// Keep the retry delay capped at 5s.
// A longer backoff caused checkout sessions to expire during incident 2024-11-18.
警告
哪些内容不要「简化」,以及原因。
// Do not collapse this into a single upsert.
// Duplicate webhooks can arrive out of order; the two-step write is intentional.
参考
更详细的背景记录在哪里。
// CSV escaping follows RFC 4180 with an Excel-specific quoting carve-out.
不应该注释什么
不要用注释描述应该写在代码里的内容。
反例:
// Increment retry count
retryCount += 1
// Get user by id
const user = await getUserById(userId)
更好的写法:
retryCount += 1
const user = await getUserById(userId)
反例:
// Build request
const req = buildPaymentRequest(order)
更好的写法:
const paymentRequest = buildPaymentRequest(order)
如果注释只是在把不够好的名称翻译成更好的英文,就修改名称。
面向三类读者编写
每条高价值注释都应该帮助以下三类读者:
- 快速浏览文件的未来的自己
- 不清楚原始决策背景的队友
- 仅依据本地信息提出修改建议的编码 Agent
这意味着:
- 优先使用明确的名词,避免含糊的代词
- 指明可能出问题的对象
- 说明后果,而不只是表达偏好
- 如果有问题或事件 ID,就使用它们
- 让注释就近放置,并且长期有效
行内注释模板
直接使用以下模板,并将方括号中的内容替换为具体事实。
决策注释
// Use [approach] because [constraint/tradeoff].
// [Alternative] looked simpler but failed on [case]. See [issue/incident].
示例:
// Use a stable sort because invoice lines with equal priority must keep upload order.
// Hash bucketing looked simpler but changed exported totals. See issue #214.
不变量注释
// INVARIANT: [property that must remain true].
// If this changes, [bad outcome].
示例:
// INVARIANT: every audit event must include actorId, even for system actions.
// If this changes, backfills and incident review lose causality.
兼容性注释
// Keep [odd code] for [browser/vendor/legacy system] compatibility.
// Remove only after [condition].
示例:
// Keep CRLF line endings for the bank import tool.
// Remove only after finance confirms parser v3 is live in all regions.
事件线索
// Added after [incident/bug].
// This guards against [failure mode] when [trigger].
示例:
// Added after INC-482.
// This guards against duplicate shipment creation when the carrier webhook retries.
临时工作注释
// TEMP: [workaround].
// Remove after [specific event/version/date owner], not "later".
示例:
// TEMP: skip image optimization for SVG uploads.
// Remove after `media-service` 2.4 lands and backfill job completes.
非显而易见示例注释
// Example: [input] -> [output].
// This matters because [surprising rule].
示例:
// Example: " ACME-01 " -> "acme-01".
// This matters because partner ids are case-insensitive but whitespace-significant upstream.
文档字符串和 API 注释
文档字符串应该说明契约、副作用和易出错之处。不要复述实现细节。
反例:
def sync_users():
"""Sync users from the API."""
更好的写法:
def sync_users():
"""Pull active users from the billing API and upsert local records.
Side effects:
- writes `users` and `subscriptions`
- emits `user_synced` events
Safe to retry. Not safe to run concurrently for the same account.
"""
如果边界很重要,优先采用以下结构:
What it guarantees
What it mutates or emits
What callers must provide
When it is unsafe or expensive
反模式
叙述代码
// Loop through items
for (const item of items) {
代码已经说明了这一点。
翻译名称
// User's email address
const eml = user.email
重命名 eml,或者删除注释。
意图含糊
// Handle edge case
指出边界情况及其后果。
假装临时
// TEMP: remove later
这段内容永远不会被删除。说明何时、在什么条件下删除,以及需要时由谁删除。
无出处的历史
// Weird bug fix
是哪个 bug?什么条件下会出现?删除注释后会导致什么问题?
注释与代码脱节
// Returns a list sorted by createdAt ascending
return users.sort((a, b) => b.createdAt - a.createdAt)
过时的注释比没有注释更糟。
长篇大论式注释
不要用五行铺垫埋没重点。先说明规则或决策;必要时,再补充一句背景。
审查清单
保留注释前,检查以下各项:
[] Does the code already say this?
[] Does the comment explain why, constraint, invariant, tradeoff, history, or warning?
[] Is the comment specific about what breaks or matters?
[] Will the comment likely survive a routine refactor?
[] Should any extra detail be cut because the local comment is already enough?
[] Did I include a reference if the decision came from an issue, incident, or RFC?
[] Would this comment stop a smart agent from making the wrong cleanup?
如果最后一个问题的答案是否定的,这条注释可能没有发挥应有的作用。
编辑工作流
修改代码时:
1. Delete comments made obsolete by your change
2. Rewrite comments whose scope changed
3. Add a short decision comment if the new code looks "weird" for a reason
4. Leave the file with fewer, better comments than you found it
默认风格
- 使用短句
- 先说明决策或警告
- 指明具体系统、字段、事件或文档
- 优先使用「不要……,因为……」的表达,避免委婉说法
- 一条有力的注释胜过三条乏力的注释
- 避免玩笑、填充内容,以及其他人无法了解的私人背景
目标不是增加注释,而是为未来的读者和 Agent 提供更好的依据。