code-comments について
code-comments は、開発者やコーディングエージェント向けのコードコメント作成ガイドです。まずコードを明確にし、実装だけでは伝わらない意図、制約、不変条件を短く局所的なコメントで補う方針を示します。
主な機能
- 01コードの整理で意図を明確化
- 02理由・制約・不変条件を記述
- 03コメントを短くコードの近くに配置
- 04判断や互換性のテンプレートを提供
- 05Docstring とレビュー項目を解説
活用シーン
- 01自明でない実装の背景を説明
- 02維持すべきコードの不変条件を記録
- 03互換性の制約や過去の判断を文書化
- 04古いコメントや重複コメントを見直す
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ caidanw/ skills --skill code-commentsインストール後、Claude Code で/code-commentsを入力して読み込まれたか確認します。
詳細
コードコメント
what は構造で説明できるコードを書きます。コメントでは、後から読む人やエージェントが「なぜそうするのか」「なぜ別の方法ではないのか」「何を維持しなければならないのか」「ここですでに何が起きたのか」を理解できるようにします。
基本ルール
次の順序で進めます。
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
良いコメントは誤った編集を減らします。優れたコメントは、人やエージェントが過去の失敗を繰り返すのを防ぎます。
コメントの判断基準
コメントを書く前に、次のことを確認します。
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)
分かりにくい名前をより良い英語に言い換えるだけのコメントなら、名前を修正してください。
3 つの読者に向けて書く
重要なコメントは、次の 3 者すべてに役立つものでなければなりません。
- ファイルを素早く確認する、将来の自分
- 元の判断に至った経緯を知らないチームメイト
- 手元の情報だけをもとに編集を提案するコーディングエージェント
そのためには、次のようにします。
- 曖昧な代名詞より、明確な名詞を使います
- 壊れる対象を明記します
- 好みだけでなく、結果を述べます
- 存在する場合は、課題やインシデントの 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.
Docstring と API コメント
Docstring では、契約、影響、注意が必要な点を説明します。実装をそのまま言い換えないでください。
悪い例:
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
どのバグですか。どんな条件で発生しますか。削除すると何が壊れますか。
実態と食い違うコメント
// Returns a list sorted by createdAt ascending
return users.sort((a, b) => b.createdAt - a.createdAt)
古くなったコメントは、コメントがないより悪いです。
長文のコメント
5 行の前置きで要点を埋もれさせないでください。まずルールや判断を示し、必要であれば背景を 1 文追加します。
レビュー用チェックリスト
コメントを残す前に、次の項目すべてを確認してください。
[] 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
基本スタイル
- 短い文を使います
- 判断や警告から始めます
- 具体的なシステム、フィールド、インシデント、または文書の名前を挙げます
- あいまいな表現より
Do not ... because ...を使います - 弱いコメントを 3 つ書くより、強いコメントを 1 つ書きます
- 冗談、埋め草、他の人が知る手段のない内輪の情報は避けます
目標はコメントの数を増やすことではありません。将来の読者やエージェントが判断するための、より確かな根拠を残すことです。