cc-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese


Claude Code Best Practices

Claude Code 最佳实践

Based on the official Anthropic documentation at https://code.claude.com/docs/en/best-practices.
The single most important constraint: Claude's context window fills up fast, and performance degrades as it fills. Every best practice flows from this.

基于 Anthropic 官方文档:https://code.claude.com/docs/en/best-practices.
最核心的约束条件:**Claude的上下文窗口会快速占满,且性能会随其占满而下降。**所有最佳实践均以此为出发点。

Instructions

操作指南

Step 1: Always give Claude a way to verify its work

步骤1:始终为Claude提供验证工作成果的方式

Provide a runnable check (test suite, build exit code, linter, diff script) so Claude can confirm success independently. Ask for evidence (test output, command result), not just assertions.
提供可运行的检查机制(测试套件、构建退出码、代码检查工具、差异脚本),让Claude能独立确认任务成功。要求提供证据(测试输出、命令执行结果),而非仅断言。

Step 2: Use the Explore → Plan → Implement workflow for non-trivial tasks

步骤2:针对非简单任务使用「探索→计划→实施」工作流

Enter
/plan
mode, let Claude read the codebase first, then draft a plan before writing any code. Exit plan mode to implement. Skip this only for small, obvious changes.
进入
/plan
模式,先让Claude读取代码库,再编写计划,最后才开始写代码。完成计划后退出模式进行实施。仅在处理微小、明确的变更时可跳过此步骤。

Step 3: Write specific, scoped prompts

步骤3:编写具体、限定范围的提示词

Name files (
@filename
), describe symptoms rather than guesses, reference existing patterns. Vague prompts produce vague results.
指定文件名(
@filename
)、描述问题症状而非主观猜测、参考现有代码模式。模糊的提示词会产生模糊的结果。

Step 4: Keep CLAUDE.md short and actionable

步骤4:保持CLAUDE.md简洁且具备可操作性

Include only what Claude cannot infer from the code. Every line should answer: "Would removing this cause Claude to make mistakes?" If not — cut it.
仅包含Claude无法从代码中推断出的信息。每一行都应回答:「删除这一行会导致Claude出错吗?」如果不会——就删掉。

Step 5: Manage context aggressively

步骤5:主动管理上下文

Use
/clear
between unrelated tasks. After two failed corrections on the same issue: clear and write a better prompt. Use
/compact <hint>
to compact with focus.
在处理不相关任务之间使用
/clear
命令。针对同一问题两次修正失败后:清空上下文并编写更优的提示词。使用
/compact <hint>
命令聚焦压缩上下文。

Step 6: Use subagents for investigation and review

步骤6:使用子代理进行调查和评审

Let subagents explore unfamiliar code or review your implementation — they run in a fresh context without bias toward the code they just wrote.

让子代理探索不熟悉的代码或评审你的实现——它们在全新上下文中运行,不会对刚编写的代码产生偏见。

Examples

示例

Example 1: Implementing a feature correctly

示例1:正确实现功能

User says: "I keep getting flaky results when I ask Claude to implement something"
Actions:
  1. Add a verification step to the prompt: "write a validateEmail function — run the existing test suite after implementing, show me the output"
  2. If no tests exist: "write the function AND write tests for it, run them, show results"
  3. Set a Stop hook to block turn completion until tests pass
Result: Claude iterates until tests pass instead of stopping when the code looks done.
用户提问:"我让Claude实现功能时总是得到不稳定的结果"
操作流程:
  1. 在提示词中添加验证步骤:"编写一个validateEmail函数——实现后运行现有测试套件,并展示输出结果"
  2. 如果没有测试:"编写该函数并为其编写测试用例,运行测试并展示结果"
  3. 设置Stop钩子,阻止对话结束直到测试通过
结果:Claude会迭代直到测试通过,而非在代码看起来完成时就停止。

Example 2: Tackling a complex, multi-file change

示例2:处理复杂的多文件变更

User says: "How should I approach a big refactor across 10 files?"
Actions:
  1. Enter
    /plan
    mode — Claude explores without making changes
  2. Ask: "read the affected files and write a step-by-step implementation plan"
  3. Edit the plan directly with
    Ctrl+G
    if needed
  4. Exit plan mode — Claude implements and commits per the plan
  5. Run a subagent to review the diff in a fresh context
Result: Structured refactor with a reviewable plan, no context-thrashing from mixed explore/write turns.
用户提问:"我该如何处理涉及10个文件的大型重构?"
操作流程:
  1. 进入
    /plan
    模式——Claude仅探索不做变更
  2. 提问:"读取受影响的文件并编写分步实施计划"
  3. 如有需要,使用
    Ctrl+G
    直接在编辑器中编辑计划
  4. 退出计划模式——Claude按照计划实施并提交代码
  5. 运行子代理在全新上下文中评审差异
结果:结构化重构且计划可评审,不会因混合探索/编写环节导致上下文混乱。

Example 3: Claude keeps repeating the same mistake

示例3:Claude重复犯同一错误

User says: "I've corrected Claude 3 times on the same issue and it keeps doing it wrong"
Actions:
  1. Run
    /clear
    — start a fresh context
  2. Identify what was missing from the original prompt (missing constraint, missing example, ambiguous scope)
  3. Write a new initial prompt that includes the constraint explicitly: "IMPORTANT: do not use mocks in these tests — use real database connections"
  4. Add the constraint to CLAUDE.md if it applies project-wide
Result: Clean session with a better-specified prompt outperforms a long session with accumulated corrections.


用户提问:"我已经纠正Claude三次同一问题,但它还是出错"
操作流程:
  1. 运行
    /clear
    ——开启全新上下文
  2. 找出原提示词中缺失的内容(遗漏的约束、缺失的示例、模糊的范围)
  3. 编写新的初始提示词,明确包含约束条件:"重要提示:这些测试不要使用mock——使用真实数据库连接"
  4. 如果该约束适用于整个项目,将其添加到CLAUDE.md中
结果:使用更明确提示词的全新会话,性能优于累积多次修正的长会话。


1. Give Claude a way to verify its work

1. 为Claude提供验证工作成果的方式

Claude stops when the work looks done. Without a runnable check, you become the verification loop. Provide something that returns a pass/fail signal Claude can read: a test suite, a build exit code, a linter, a script that diffs output.
  • Ask Claude to run the check and iterate in the same prompt.
  • Set
    /goal
    conditions for multi-turn verification.
  • Use a Stop hook to block the turn from ending until a script passes.
  • Use a verification subagent so the reviewer has a fresh context.
Ask Claude to show evidence (test output, command result, screenshot) rather than just asserting success.
Example upgrade:
Before: "implement a function that validates email addresses" After: *"write a validateEmail function. test cases: user@example.com → true,
invalid → false. run the tests after implementing"*

Claude在工作看起来完成时就会停止。没有可运行的检查机制,你就成了验证环节。提供能让Claude读取到通过/失败信号的机制:测试套件、构建退出码、代码检查工具、输出差异脚本。
  • 要求Claude在同一提示词中运行检查并迭代。
  • 为多轮验证设置
    /goal
    条件。
  • 使用Stop钩子阻止对话结束直到脚本通过。
  • 使用验证子代理,让评审者拥有全新上下文。
要求Claude展示证据(测试输出、命令结果、截图),而非仅断言成功。
提示词优化示例:
优化前:"实现一个验证邮箱地址的函数" 优化后:"编写一个validateEmail函数。测试用例:user@example.com → true,invalid → false。实现后运行测试"

2. Explore first, then plan, then code

2. 先探索,再计划,最后编码

Use plan mode (
/plan
or the UI toggle) to separate reading from writing.
  1. Explore — enter plan mode; Claude reads files without making changes.
  2. Plan — ask Claude to write a detailed implementation plan. Press
    Ctrl+G
    to open the plan in your editor for direct edits.
  3. Implement — exit plan mode; Claude codes and verifies against the plan.
  4. Commit — ask Claude to commit and open a PR.
Skip planning when the scope is clear and the fix is small (typo, rename, single-line change). Plan mode adds overhead — use it when the change touches multiple files or you are unfamiliar with the code.

使用计划模式
/plan
或UI切换按钮)将读取与编写分离。
  1. 探索——进入计划模式;Claude仅读取文件不做变更。
  2. 计划——要求Claude编写详细的实施计划。按
    Ctrl+G
    在编辑器中打开计划进行直接编辑。
  3. 实施——退出计划模式;Claude编码并对照计划验证。
  4. 提交——要求Claude提交代码并创建PR。
当范围明确且修复内容微小(拼写错误、重命名、单行变更)时可跳过计划。计划模式会增加开销——当变更涉及多个文件或你不熟悉代码时再使用。

3. Provide specific context in your prompts

3. 在提示词中提供具体上下文

Claude can infer intent but cannot read your mind.
StrategyVagueSpecific
Scope the task"add tests for foo.py""write a test for foo.py covering the edge case where the user is logged out. avoid mocks."
Point to sources"why does ExecutionFactory have a weird API?""look through ExecutionFactory's git history and summarize how its API evolved"
Reference patterns"add a calendar widget""look at HotDogWidget.php as a pattern reference and follow it to implement a calendar widget"
Describe the symptom"fix the login bug""users report login fails after session timeout. check src/auth/ token refresh. write a failing test, then fix it."
Rich context techniques:
  • Use
    @filename
    to reference files directly.
  • Paste screenshots or drag images into the prompt.
  • Pipe data:
    cat error.log | claude
  • Give URLs for documentation (allowlist domains via
    /permissions
    ).

Claude能推断意图但无法读取你的想法。
策略模糊表述具体表述
限定任务范围"为foo.py添加测试""为foo.py编写测试,覆盖用户未登录的边缘场景。不要使用mock。"
指定参考来源"为什么ExecutionFactory的API这么奇怪?""查看ExecutionFactory的git历史,总结其API的演变过程"
参考代码模式"添加一个日历组件""参考HotDogWidget.php的代码模式,实现一个日历组件"
描述问题症状"修复登录bug""用户反馈会话超时后登录失败。检查src/auth/的token刷新逻辑。先编写失败测试用例,再修复问题。"
丰富上下文技巧:
  • 使用
    @filename
    直接引用文件。
  • 在提示词中粘贴截图或拖拽图片。
  • 管道传输数据:
    cat error.log | claude
  • 提供文档URL(通过
    /permissions
    添加域名白名单)。

4. Write an effective CLAUDE.md

4. 编写高效的CLAUDE.md

CLAUDE.md is read at the start of every session. Keep it short and human-readable — bloated CLAUDE.md files cause Claude to ignore actual instructions.
Include:
  • Bash commands Claude cannot guess (e.g., build/test commands)
  • Code style rules that differ from language defaults
  • Testing instructions and preferred test runners
  • Repository etiquette (branch naming, PR conventions)
  • Architectural decisions specific to the project
  • Developer environment quirks, required env vars
  • Common gotchas or non-obvious behaviors
Exclude:
  • Anything Claude can figure out by reading the code
  • Standard language conventions Claude already knows
  • Detailed API documentation (link instead)
  • Self-evident practices like "write clean code"
For each line: "Would removing this cause Claude to make mistakes?" If not, cut it.
Use
/context
to confirm Claude loaded the file. Use
@path/to/file
imports in CLAUDE.md to pull in other files selectively.

CLAUDE.md会在每个会话开始时被读取。保持其简洁且易读——臃肿的CLAUDE.md会导致Claude忽略实际指令。
需包含内容:
  • Claude无法猜测的Bash命令(如构建/测试命令)
  • 与语言默认规则不同的代码风格规范
  • 测试说明及首选测试运行器
  • 仓库规范(分支命名、PR约定)
  • 项目特定的架构决策
  • 开发环境特性、必需的环境变量
  • 常见陷阱或不明显的行为
需排除内容:
  • Claude通过读取代码就能了解的信息
  • Claude已掌握的标准语言约定
  • 详细的API文档(改为链接)
  • 诸如"编写整洁代码"这类不言自明的做法
对于每一行内容:「删除这一行会导致Claude出错吗?」如果不会,就删掉。
使用
/context
命令确认Claude已加载该文件。在CLAUDE.md中使用
@path/to/file
导入其他文件。

5. Manage session context aggressively

5. 主动管理会话上下文

  • /clear
    — reset context between unrelated tasks.
  • /compact <instructions>
    — compact with focus (e.g.,
    /compact Focus on API changes
    ).
  • Esc + Esc
    /
    /rewind
    — open the rewind menu; restore conversation and/or code state to any previous checkpoint.
  • /btw
    — ask a quick side-question; answer appears in an overlay and never enters conversation history.
After two failed corrections on the same issue: run
/clear
and write a better initial prompt incorporating what you learned. A clean session with a better prompt outperforms a long session with accumulated corrections.
Customize compaction in CLAUDE.md:
*"When compacting, always preserve the full list of modified files and any
test commands"*

  • /clear
    ——在不相关任务之间重置上下文。
  • /compact <instructions>
    ——聚焦压缩上下文(例如:
    /compact Focus on API changes
    )。
  • Esc + Esc
    /
    /rewind
    ——打开回退菜单;将对话和/或代码状态恢复到之前的任意 checkpoint。
  • /btw
    ——快速提问;答案会在浮层中显示,不会进入对话历史。
**针对同一问题两次修正失败后:**运行
/clear
并结合所学编写更优的初始提示词。使用更优提示词的全新会话,性能优于累积多次修正的长会话。
在CLAUDE.md中自定义压缩规则:
"压缩时,始终保留完整的已修改文件列表及所有测试命令"

6. Use subagents for investigation and review

6. 使用子代理进行调查和评审

Subagents run in their own context window and report back summaries, keeping your main conversation clean.
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
After implementation:
use a subagent to review this code for edge cases
Use
/code-review
skill for a bug-focused adversarial review of the current diff.

子代理在独立的上下文窗口中运行,并返回总结内容,保持主对话整洁。
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
完成实施后:
use a subagent to review this code for edge cases
使用
/code-review
技能对当前差异进行聚焦于bug的对抗性评审。

7. Automate and scale

7. 自动化与规模化

Non-interactive mode — integrate Claude into CI, pre-commit hooks, scripts:
bash
claude -p "List all API endpoints" --output-format json
claude -p "Analyze this log file" --output-format stream-json --verbose
Fan out across files — loop through tasks:
bash
for file in $(cat files.txt); do
  claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
    --allowedTools "Edit,Bash(git commit *)"
done
Parallel sessions — run multiple Claude sessions with git worktrees so edits don't collide. Writer/Reviewer pattern:
  • Session A implements a feature.
  • Session B reviews the diff in a fresh context (no bias toward the code it just wrote).
Auto mode — uninterrupted execution with background safety checks:
bash
claude --permission-mode auto -p "fix all lint errors"

非交互模式——将Claude集成到CI、预提交钩子、脚本中:
bash
claude -p "List all API endpoints" --output-format json
claude -p "Analyze this log file" --output-format stream-json --verbose
多文件批量处理——循环执行任务:
bash
for file in $(cat files.txt); do
  claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
    --allowedTools "Edit,Bash(git commit *)"
done
并行会话——使用git工作树运行多个Claude会话,避免编辑冲突。编写者/评审者模式:
  • 会话A实现功能。
  • 会话B在全新上下文中评审差异(不会对刚编写的代码产生偏见)。
自动模式——带后台安全检查的不间断执行:
bash
claude --permission-mode auto -p "fix all lint errors"

8. Common failure patterns and quick reference

8. 常见失败模式与快速参考

For the full failure patterns table, all CLI commands, and non-interactive mode examples, consult
references/commands.md
.
完整的失败模式表格、所有CLI命令及非交互模式示例,请查阅
references/commands.md