Chapter 18 · Advanced Techniques and Best Practices
Chapter goals: Master prompt techniques that double Claude Code's output quality — precise instructions, task decomposition, context optimization, and hallucination verification — and form your own efficient workflow.
18.1 Precise Instructions: Vagueness Is the Root of All Evil
"Add pagination to the search feature" — this may be sufficient for a human colleague, but for an agent it is full of ambiguity: cursor-based or offset? How many per page? Should results be highlighted?
❌ Vague instruction:
> Fix this bug
✅ Precise instruction:
> test_expired_token_refresh in tests/auth.test.ts is failing.
> Error: "JWT expired before verification".
> The issue may be in src/auth/token.ts verifyToken not handling
> clock skew. First run npm test -- auth to confirm the failure,
> then locate and fix it.Three elements of a precise instruction: target file, expected behavior, verification method. When all three are present, Claude's first-attempt pass rate improves significantly.
18.2 Task Decomposition: Plan Mode and Incremental Delivery
For complex tasks, asking Claude to "do it all at once" often leads to drift midway. The better approach is a two-stage workflow:
Stage 1: Read-Only Planning
Switch to Plan Mode via Shift+Tab (or select opus via /model to提升规划质量). In this mode Claude can only read files and search — no writes:
> I want to split src/utils.js into multiple module files.
> Analyze the current structure first and propose a plan. Do not modify any code.
(Claude outputs a plan: suggest splitting into format.ts / validate.ts / api.ts ...)Stage 2: Incremental Execution
After confirming the plan, exit Plan Mode and execute step by step:
> Good plan. Start with step one: move formatDate and parseDate to date.ts,
> update all imports, then run npm test to confirm nothing broke.Why This Works
Plan Mode forces the model to完成 global思考 before动手; incremental execution lets you纠偏 at each checkpoint. Combined, they reduce the failure rate of大型重构 from "pray and hope" to "controlled iteration."
18.3 Context Optimization Tips
Keep CLAUDE.md Lean
CLAUDE.md is常驻上下文; every line consumes tokens. Best practice:
# CLAUDE.md — keep under ~100 lines
## Tech Stack
- Node 20 + TypeScript strict
- Tests: vitest, run `npm test`
- Lint: `npm run lint` (ESLint + Prettier)
## Hard Constraints
- Don't add new dependencies unless explicitly discussed
- API responses must be validated with Zod schemas
- All public functions must have JSDoc comments
## Common Commands
- Build: npm run build
- Single test: npx vitest run <file>Put detailed docs in the docs/ directory; in CLAUDE.md just write "see docs/architecture.md for details" and let the agent read on demand.
Clean Up Context Promptly
When switching to an unrelated new task, run /clear instead of accumulating历史. Old task context not onlywastes tokens but also pollutes new task output (the model may混淆 the two tasks' requirements).
Targeted References vs. Vague Talk
❌ "There's a module handling user auth in the project, help me look"
✅ "Look at the verifySession function around line 40 in src/auth/middleware.ts"Precise references let the agent直接命中 the target file, saving探索 time.
18.4 Hallucination Detection and Verification
LLMs天生倾向于"给出一个听起来合理的答案". Claude Code is no exception — it may call non-existent APIs, fabricate config names, or claim tests passed when it neveractually ran them.
The Three Axes of Verification
Axis 1: Make It Run Commands
> You said the bug is fixed. Run npm test -- auth and paste the full output.If Claude claims it修改了 code,要求 it show the diff or run tests toprove. Never accept "done" based solely on verbal claim.
Axis 2: Cross-Verify API References
When Claude uses a library API you're unfamiliar with, ask it to展示 the source:
> You used zod.string().cuid2(). Open node_modules/zod
> type definitions and confirm this方法 exists.Or spend 10 seconds checking the official docs yourself — this saves an hour of debugging hallucinated code.
Axis 3: TDD Shield
Write the test first, then have Claude实现 — the most reliable防幻觉手段:
# You write the test first (defining "correct")
npx vitest generate src/utils/date.test.ts
# Have Claude implement until all pass
claude "Implement src/utils/date.ts so all vitest cases pass. Do not modify test files."If Claude偷偷改测试 to "pass", the diff shows it immediately.
18.5 Personal Workflow Template
Combining以上 techniques, an efficient daily loop:
1. /clear ← clean start
2. Describe the task precisely (含 file paths + verification method)
3. Shift+Tab into Plan Mode ← plan first for large tasks
4. Confirm plan → execute step by step ← verification command at each step
5. Require running tests and showing output ← hallucination防护
6. git diff to review changes ← final gate
7. /compact or /clear ← free contextChapter Summary
- Three elements of precise instructions: target file, expected behavior, verification method;
- Plan Mode's "two-stage" approach (plan then execute)大幅降低大任务跑偏率;
- Keep CLAUDE.md lean; externallink detailed content让 agent read on demand;
- Hallucination defense three axes: run commands to证伪, cross-verify APIs, TDD shield;
/clearon task switch is the mostunderestimated good habit.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. Which instruction best符合 the "precise instruction" principle?
2. What is the core value of Plan Mode (Shift+Tab)?
3. What is the most reliable method to prevent Claude Code hallucinations?
4. Why is it recommended to write "see docs/architecture.md for details" in CLAUDE.md?
🛠️ Hands-on Practice
- Pick a task yourecently asked Claude to do; rewrite it as a precise instruction containing all three elements; compare the first-attempt pass rate.
- Use Plan Mode's two-stage flow for a medium-sized refactor;记录 the gap between the plan and the actual execution.
- Deliberately ask Claude about a non-existent API method (e.g. "use lodash's deepFreezeAll function…"); observe whether it fabricates usage; then practice correcting it with cross-verification.