code-comments
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Comments
代码注释
Write documentation that lives with the code it describes. Plain language. No jargon. Explain the why, not the what.
编写与所描述代码共存的文档。使用平实语言,避免行话。解释「为什么这么做」,而非「做了什么」。
Core Philosophy
核心原则
Co-location wins. Documentation in separate files drifts out of sync. Comments next to code stay accurate because they're updated together.
Write for three audiences:
- Future you, six months from now
- Teammates reading unfamiliar code
- AI assistants (Claude, Copilot) who see one file at a time
The "why" test: Before writing a comment, ask: "Does this explain why this code exists or why it works this way?" If it only restates what the code does, skip it.
就近原则优先。存放在单独文件中的文档容易与代码脱节。紧邻代码的注释会随代码一同更新,因此能保持准确性。
为三类受众编写:
- 六个月后的你自己
- 阅读陌生代码的同事
- 一次只能查看单个文件的AI助手(Claude、Copilot)
「为什么」测试:在编写注释前,先问自己:「这段注释是否解释了代码存在的原因或如此实现的理由?」如果只是重述代码的功能,那就没必要写。
Documentation Levels
文档层级
File Headers
文件头
Every file should open with a brief explanation of its purpose and how it fits into the larger system.
typescript
// UserAuthContext.tsx
//
// Manages authentication state across the app. Wraps the root component
// to provide login status, user info, and auth methods to any child.
//
// Why a context instead of Redux: Auth state is read-heavy and rarely
// changes mid-session. Context avoids the ceremony of actions/reducers
// for something this simple.swift
// NetworkRetryPolicy.swift
//
// Handles automatic retry logic for failed network requests.
// Uses exponential backoff with jitter to avoid thundering herd
// when the server comes back online after an outage.
//
// Used by: APIClient, BackgroundSyncManager
// See also: NetworkError.swift for error classificationInclude:
- What this file/module is responsible for
- Why it exists (if not obvious from the name)
- Key relationships to other parts of the codebase
- Any non-obvious design decisions
每个文件开头都应简要说明其用途,以及它在整个系统中的定位。
typescript
// UserAuthContext.tsx
//
// Manages authentication state across the app. Wraps the root component
// to provide login status, user info, and auth methods to any child.
//
// Why a context instead of Redux: Auth state is read-heavy and rarely
// changes mid-session. Context avoids the ceremony of actions/reducers
// for something this simple.swift
// NetworkRetryPolicy.swift
//
// Handles automatic retry logic for failed network requests.
// Uses exponential backoff with jitter to avoid thundering herd
// when the server comes back online after an outage.
//
// Used by: APIClient, BackgroundSyncManager
// See also: NetworkError.swift for error classification需包含内容:
- 该文件/模块的职责
- 存在的原因(如果从名称无法直接看出)
- 与代码库其他部分的关键关联
- 任何非显而易见的设计决策
Function & Method Documentation
函数与方法文档
Document the contract, not the implementation.
typescript
/**
* Calculates shipping cost based on weight and destination.
*
* Uses tiered pricing: under 1lb ships flat rate, 1-5lb uses
* regional rates, over 5lb triggers freight calculation.
*
* Returns $0 for destinations we don't ship to rather than
* throwing—caller should check `canShipTo()` first if they
* need to distinguish "free shipping" from "can't ship."
*/
function calculateShipping(weightLbs: number, zipCode: string): numberpython
def sync_user_preferences(user_id: str, prefs: dict) -> SyncResult:
"""
Pushes local preference changes to the server and pulls remote changes.
Conflict resolution: server wins for security settings, local wins
for UI preferences. See PREFERENCES.md for the full conflict matrix.
Called automatically on app foreground. Can also be triggered manually
from Settings > Sync Now.
"""Include:
- What the function accomplishes (not how)
- Non-obvious parameter constraints or edge cases
- What the return value means, especially for ambiguous cases
- Side effects (network calls, file writes, state mutations)
Skip for: Simple getters, obvious one-liners, private helpers with descriptive names.
记录契约,而非实现细节。
typescript
/**
* Calculates shipping cost based on weight and destination.
*
* Uses tiered pricing: under 1lb ships flat rate, 1-5lb uses
* regional rates, over 5lb triggers freight calculation.
*
* Returns $0 for destinations we don't ship to rather than
* throwing—caller should check `canShipTo()` first if they
* need to distinguish "free shipping" from "can't ship."
*/
function calculateShipping(weightLbs: number, zipCode: string): numberpython
def sync_user_preferences(user_id: str, prefs: dict) -> SyncResult:
"""
Pushes local preference changes to the server and pulls remote changes.
Conflict resolution: server wins for security settings, local wins
for UI preferences. See PREFERENCES.md for the full conflict matrix.
Called automatically on app foreground. Can also be triggered manually
from Settings > Sync Now.
"""需包含内容:
- 函数实现的目标(而非实现方式)
- 非显而易见的参数约束或边缘情况
- 返回值的含义,尤其是模糊场景下的说明
- 副作用(网络请求、文件写入、状态变更)
无需编写的场景:简单的getter方法、显而易见的单行代码、名称具有描述性的私有辅助函数。
Inline Comments
内联注释
Use sparingly. When you need them, explain the reasoning.
typescript
// Debounce search by 300ms to avoid hammering the API on every keystroke.
// 300ms feels responsive while cutting API calls by ~80% in user testing.
const debouncedSearch = useMemo(
() => debounce(executeSearch, 300),
[executeSearch]
);swift
// Force unwrap is safe here—viewDidLoad guarantees the storyboard
// connected this outlet. If it's nil, we want to crash immediately
// rather than fail silently later.
let tableView = tableView!python
undefined谨慎使用。当必须使用时,解释背后的原因。
typescript
// Debounce search by 300ms to avoid hammering the API on every keystroke.
// 300ms feels responsive while cutting API calls by ~80% in user testing.
const debouncedSearch = useMemo(
() => debounce(executeSearch, 300),
[executeSearch]
);swift
// Force unwrap is safe here—viewDidLoad guarantees the storyboard
// connected this outlet. If it's nil, we want to crash immediately
// rather than fail silently later.
let tableView = tableView!python
undefinedProcess oldest items first. Newer items are more likely to be
Process oldest items first. Newer items are more likely to be
modified again, so processing them last reduces wasted work.
modified again, so processing them last reduces wasted work.
queue.sort(key=lambda x: x.created_at)
undefinedqueue.sort(key=lambda x: x.created_at)
undefinedArchitectural Comments
架构注释
For code that embodies important design decisions, explain the tradeoffs.
typescript
// ARCHITECTURE NOTE: Event Sourcing for Cart
//
// Cart state is rebuilt from events (add, remove, update quantity)
// rather than stored directly. This lets us:
// - Show complete cart history to users
// - Replay events for debugging
// - Retroactively apply promotions to past actions
//
// Tradeoff: Reading current cart state requires replaying all events.
// We cache the computed state in Redis with 5min TTL to keep reads fast.
// Cache invalidation happens in CartEventHandler.swift
// WHY COORDINATOR PATTERN
//
// Navigation logic lives here instead of in view controllers because:
// 1. VCs don't need to know about each other (loose coupling)
// 2. Deep linking becomes straightforward—just call coordinator methods
// 3. Navigation is testable without instantiating UI
//
// The tradeoff is more files and indirection. Worth it for apps with
// 10+ screens; overkill for simple apps.对于承载重要设计决策的代码,解释其中的权衡。
typescript
// ARCHITECTURE NOTE: Event Sourcing for Cart
//
// Cart state is rebuilt from events (add, remove, update quantity)
// rather than stored directly. This lets us:
// - Show complete cart history to users
// - Replay events for debugging
// - Retroactively apply promotions to past actions
//
// Tradeoff: Reading current cart state requires replaying all events.
// We cache the computed state in Redis with 5min TTL to keep reads fast.
// Cache invalidation happens in CartEventHandler.swift
// WHY COORDINATOR PATTERN
//
// Navigation logic lives here instead of in view controllers because:
// 1. VCs don't need to know about each other (loose coupling)
// 2. Deep linking becomes straightforward—just call coordinator methods
// 3. Navigation is testable without instantiating UI
//
// The tradeoff is more files and indirection. Worth it for apps with
// 10+ screens; overkill for simple apps.TODO Comments
TODO注释
Make them actionable and traceable.
typescript
// TODO(pete): Extract to shared util once mobile team needs this too.
// Blocked on: Mobile API parity (see MOBILE-123)
// HACK: Workaround for Safari flexbox bug. Remove after dropping Safari 14.
// Bug report: https://bugs.webkit.org/show_bug.cgi?id=XXXXX
// FIXME: Race condition when user rapidly toggles. Need to cancel
// in-flight requests. Reproduced in issue #892.确保注释具有可操作性和可追踪性。
typescript
// TODO(pete): Extract to shared util once mobile team needs this too.
// Blocked on: Mobile API parity (see MOBILE-123)
// HACK: Workaround for Safari flexbox bug. Remove after dropping Safari 14.
// Bug report: https://bugs.webkit.org/show_bug.cgi?id=XXXXX
// FIXME: Race condition when user rapidly toggles. Need to cancel
// in-flight requests. Reproduced in issue #892.Language-Specific Patterns
语言特定模式
See references/language-examples.md for detailed examples in:
- TypeScript/JavaScript (JSDoc, TSDoc patterns)
- Swift (documentation comments, MARK pragmas)
- Python (docstrings, type hint documentation)
- React/Next.js (component documentation patterns)
查看 references/language-examples.md 获取以下语言的详细示例:
- TypeScript/JavaScript(JSDoc、TSDoc 模式)
- Swift(文档注释、MARK 编译指令)
- Python(文档字符串、类型提示文档)
- React/Next.js(组件文档模式)
Writing Style
写作风格
Plain language. Write like you're explaining to a smart colleague who doesn't have context.
Active voice. "This function validates..." not "Validation is performed..."
Be specific. "Retries 3 times with 1s backoff" not "Handles retries."
Skip the obvious. If the code says , don't comment "checks if user is admin."
user.isAdminDate things that expire. Workarounds, version-specific code, and temporary solutions should note when they can be removed.
Reference constants, don't duplicate values. When a behavior is controlled by a constant, reference it by name—don't restate its value in the comment.
rust
// Bad: duplicates the value, will drift when constant changes
/// Returns true if stale (not updated in last 5 minutes)
pub fn is_stale(&self) -> bool { ... }
// Good: references the constant
/// Returns true if stale (not updated within [`STALE_THRESHOLD_SECS`])
pub fn is_stale(&self) -> bool { ... }Unit translations for magic numbers are fine () since they add clarity, not duplication.
1048576 // 1MB平实语言。就像在向一位缺乏上下文的聪明同事解释一样。
主动语态。使用「此函数验证……」而非「验证由……执行」。
具体明确。使用「以1秒间隔重试3次」而非「处理重试逻辑」。
跳过显而易见的内容。如果代码写的是,就不要注释「检查用户是否为管理员」。
user.isAdmin为过期内容标注时间。针对临时解决方案、版本特定代码和变通方案,应注明可移除的时间节点。
引用常量,而非重复值。当行为由常量控制时,引用常量名称——不要在注释中重复其值。
rust
// Bad: duplicates the value, will drift when constant changes
/// Returns true if stale (not updated in last 5 minutes)
pub fn is_stale(&self) -> bool { ... }
// Good: references the constant
/// Returns true if stale (not updated within [`STALE_THRESHOLD_SECS`])
pub fn is_stale(&self) -> bool { ... }对于魔法数字,标注单位转换是可行的(如),因为这能增加清晰度,而非重复内容。
1048576 // 1MB