code-comments by petekp/claude-code-setup
npx skills add https://github.com/petekp/claude-code-setup --skill code-comments编写与代码共存的文档。使用通俗语言。避免术语。解释为什么,而不是是什么。
共处一处胜于分离。 独立文件中的文档容易不同步。与代码相邻的注释能保持准确,因为它们会一同更新。
为三类读者而写:
“为什么”测试: 在写注释之前,问自己:“这解释了这段代码为什么存在或为什么这样工作吗?”如果它只是复述代码是做什么的,那就跳过。
每个文件开头都应简要说明其目的以及它如何融入更大的系统。
// UserAuthContext.tsx
//
// 管理整个应用程序的身份验证状态。包装根组件,
// 为任何子组件提供登录状态、用户信息和身份验证方法。
//
// 为什么使用 Context 而不是 Redux:身份验证状态读取频繁,
// 在会话中很少改变。对于如此简单的事情,Context 避免了 actions/reducers 的繁琐。
// NetworkRetryPolicy.swift
//
// 处理失败网络请求的自动重试逻辑。
// 使用带抖动的指数退避,以避免服务器在中断后恢复时出现惊群效应。
//
// 使用者:APIClient, BackgroundSyncManager
// 另见:NetworkError.swift 用于错误分类
包含:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
记录契约,而非实现。
/**
* 根据重量和目的地计算运费。
*
* 使用分层定价:1磅以下按统一费率,1-5磅使用区域费率,
* 超过5磅则触发货运计算。
*
* 对于我们不运送的目的地返回 $0 而不是抛出异常——
* 如果调用者需要区分“免运费”和“无法运送”,应首先检查 `canShipTo()`。
*/
function calculateShipping(weightLbs: number, zipCode: string): number
def sync_user_preferences(user_id: str, prefs: dict) -> SyncResult:
"""
将本地偏好设置更改推送到服务器并拉取远程更改。
冲突解决:安全设置以服务器为准,UI 偏好设置以本地为准。
完整的冲突矩阵请参见 PREFERENCES.md。
在应用切换到前台时自动调用。也可以从 设置 > 立即同步 手动触发。
"""
包含:
可跳过: 简单的 getter、明显的一行代码、具有描述性名称的私有辅助函数。
谨慎使用。需要时,解释其背后的原因。
// 将搜索防抖设为 300ms,以避免每次按键都冲击 API。
// 300ms 在用户测试中既感觉响应迅速,又将 API 调用减少了约 80%。
const debouncedSearch = useMemo(
() => debounce(executeSearch, 300),
[executeSearch]
);
// 这里强制解包是安全的——viewDidLoad 保证了 storyboard
// 连接了这个 outlet。如果它是 nil,我们希望立即崩溃,
// 而不是在以后静默失败。
let tableView = tableView!
# 先处理最旧的项目。较新的项目更有可能被再次修改,
# 所以最后处理它们可以减少浪费的工作。
queue.sort(key=lambda x: x.created_at)
对于体现重要设计决策的代码,解释其权衡。
// 架构说明:购物车的事件溯源
//
// 购物车状态是从事件(添加、移除、更新数量)重建而来,
// 而不是直接存储。这让我们能够:
// - 向用户展示完整的购物车历史
// - 重放事件以进行调试
// - 追溯性地将促销应用于过去的操作
//
// 权衡:读取当前购物车状态需要重放所有事件。
// 我们在 Redis 中缓存计算出的状态,TTL 为 5 分钟,以保持读取速度。
// 缓存失效在 CartEventHandler 中处理。
// 为什么使用协调器模式
//
// 导航逻辑放在这里而不是视图控制器中,因为:
// 1. 视图控制器不需要相互了解(松耦合)
// 2. 深度链接变得简单直接——只需调用协调器方法
// 3. 无需实例化 UI 即可测试导航
//
// 权衡是更多的文件和间接性。对于拥有 10+ 个屏幕的应用是值得的;
// 对于简单的应用来说则过度设计了。
使其具有可操作性和可追溯性。
// TODO(pete):一旦移动团队也需要这个,就提取到共享工具中。
// 阻塞于:移动 API 对等(参见 MOBILE-123)
// HACK:针对 Safari flexbox bug 的变通方法。在放弃 Safari 14 支持后移除。
// 错误报告:https://bugs.webkit.org/show_bug.cgi?id=XXXXX
// FIXME:用户快速切换时的竞态条件。需要取消进行中的请求。
// 在 issue #892 中复现。
详细示例请参见 references/language-examples.md:
通俗语言。 就像你在向一位聪明但没有上下文的同事解释一样写作。
主动语态。 “此函数验证...”而非“执行验证...”
具体明确。 “重试 3 次,退避 1 秒”而非“处理重试”。
跳过显而易见的。 如果代码写的是 user.isAdmin,就不要注释“检查用户是否是管理员”。
标注会过期的内容。 变通方法、特定版本代码和临时解决方案应注明何时可以移除。
引用常量,不要重复其值。 当行为由常量控制时,通过名称引用它——不要在注释中重复其值。
// 不好:重复了值,当常量改变时会不同步
/// 如果过期(在过去 5 分钟内未更新)则返回 true
pub fn is_stale(&self) -> bool { ... }
// 好:引用了常量
/// 如果过期(在 [`STALE_THRESHOLD_SECS`] 内未更新)则返回 true
pub fn is_stale(&self) -> bool { ... }
对于魔数,单位转换是可以的(1048576 // 1MB),因为它们增加了清晰度,而不是重复。
每周安装量
99
代码仓库
GitHub 星标数
20
首次出现
2026 年 1 月 26 日
安全审计
安装于
opencode89
codex88
github-copilot87
gemini-cli86
kimi-cli82
amp81
Write documentation that lives with the code it describes. Plain language. No jargon. Explain the why , not the what.
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:
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.
Every file should open with a brief explanation of its purpose and how it fits into the larger system.
// 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.
// 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
Include:
Document the contract, not the implementation.
/**
* 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): number
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:
Skip for: Simple getters, obvious one-liners, private helpers with descriptive names.
Use sparingly. When you need them, explain the reasoning.
// 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]
);
// 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!
# Process oldest items first. Newer items are more likely to be
# modified again, so processing them last reduces wasted work.
queue.sort(key=lambda x: x.created_at)
For code that embodies important design decisions, explain the tradeoffs.
// 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.
// 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.
Make them actionable and traceable.
// 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.
See references/language-examples.md for detailed examples in:
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 user.isAdmin, don't comment "checks if user is admin."
Date 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.
// 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 (1048576 // 1MB) since they add clarity, not duplication.
Weekly Installs
99
Repository
GitHub Stars
20
First Seen
Jan 26, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode89
codex88
github-copilot87
gemini-cli86
kimi-cli82
amp81
Kotlin 开发模式与最佳实践 | 构建健壮高效应用程序的惯用指南
1,000 周安装
AI旅行助手 - 智能行程规划工具,整合TikTok/Instagram/Expedia等多平台数据
136 周安装
YouTube视频上传工具 - 命令行自动化上传与元数据管理 | Claude技能库
134 周安装
Python PPTX 库教程:自动化创建、编辑 PowerPoint 演示文稿代码示例
146 周安装
掌握AnimatePresence:Framer Motion退出动画最佳实践与代码审查指南
147 周安装
CCXT 开发指南:加密货币交易 API 库使用教程、问题调试与最佳实践
150 周安装
Upstash向量数据库技能:快速实现语义搜索与AI应用开发
158 周安装