🏆Lesson 26

Best Practices for Claude Code

Patterns that consistently produce better results — from how you phrase prompts and manage context, to parallelising work and avoiding the traps that slow most people down.

Context managementPrompt qualityExplore → Plan → CodeParallel sessionsVerification

The one constraint that shapes everything

Claude's context window holds your entire conversation — every message, every file it read, every command output. It fills up fast. A single debugging session can consume tens of thousands of tokens, and performance degrades as it fills. Claude may start overlooking earlier instructions or making more mistakes.

Almost every best practice in this lesson flows from this one constraint: manage context carefully, keep prompts focused, and reset often.

1. Always give Claude a way to verify its work

💡 Tip: This is the single highest-leverage thing you can do. Claude performs dramatically better when it can check its own output — run tests, compare screenshots, validate a script result.

Without verification criteria, Claude produces something that looks right but may not work. You become the only feedback loop, and every mistake needs your attention.

❌ Vague
implement a function that validates email addresses
✅ Specific
write a validateEmail function. example test cases: user@example.com → true invalid → false user@.com → false run the tests after implementing
❌ Vague
make the dashboard look better
✅ Specific
[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them
❌ Vague
the build is failing
✅ Specific
the build fails with this error: [paste error]. fix it and verify the build succeeds. address the root cause — don't suppress the error

2. Explore first, then plan, then code

Letting Claude jump straight to coding risks solving the wrong problem. Use plan mode to separate research from implementation.

🔍
Exploreplan mode

Claude reads files and answers questions without making any changes. Understand the codebase before touching it.

read /src/auth and understand how sessions and login work. also look at how environment variables are managed.
📋
Planplan mode

Ask Claude for a detailed implementation plan. Press Ctrl+G to open and edit the plan before Claude starts coding.

I want to add Google OAuth. What files need to change? What's the session flow? Create a plan.
⚙️
Implementdefault mode

Switch out of plan mode. Claude codes against the plan and verifies with tests.

implement the OAuth flow from your plan. write tests for the callback handler, run the suite and fix any failures.
Commitdefault mode

Ask Claude to commit with a descriptive message and open a PR.

commit with a descriptive message and open a PR
ℹ️ Info: Skip the plan for small, obvious tasks — fixing a typo, adding a log line, renaming a variable. Planning adds overhead. Use it when you're unsure of the approach or when the change spans multiple files.

3. Write specific prompts

The more precise your instructions, the fewer corrections you need. Claude can infer intent but it can't read your mind. Reference files, mention constraints, and point to examples.

❌ Vague
add tests for foo.py
✅ Specific
write a test for foo.py covering the edge case where the user is logged out. avoid mocks.
❌ Vague
fix the login bug
✅ Specific
users report login fails after session timeout. check src/auth/, especially token refresh. write a failing test that reproduces it, then fix it
❌ Vague
add a calendar widget
✅ Specific
look at HotDogWidget.php to understand the widget pattern. follow it to build a calendar widget: pick a month, paginate year. no new libraries — only existing dependencies.

You can also provide rich input: use @filename to reference files directly, paste screenshots by copying and dropping into the prompt, pipe data with cat error.log | claude, or paste a URL for Claude to fetch documentation.

4. Write an effective CLAUDE.md

CLAUDE.md is loaded at the start of every session. Include bash commands, code style rules, and workflow conventions that differ from sensible defaults. Run /init to generate a starter file from your current project.

CLAUDE.md
# Code style
- Use ES modules (import/export), not CommonJS (require)
- Destructure imports when possible

# Workflow
- Always typecheck after a series of code changes
- Run single tests, not the full suite, for speed

# Repo etiquette
- Branch names: feat/<ticket>  fix/<ticket>
- PR titles must reference a ticket number

For each line ask: "Would removing this cause Claude to make a mistake?" If not, cut it. A bloated CLAUDE.md causes Claude to miss important rules buried in the noise.

✅ Include❌ Skip
Bash commands Claude can't guessThings Claude can figure out from code
Code style that differs from defaultsStandard language conventions
Test runner preferencesDetailed API docs — link instead
Branch naming & PR conventionsInformation that changes frequently
Non-obvious architectural decisionsSelf-evident rules like 'write clean code'
💡 Tip: Check CLAUDE.md into git so your whole team benefits. It compounds in value over time. You can also add CLAUDE.local.md for personal overrides — gitignore it so it stays private.

5. Manage context aggressively

Long sessions accumulate irrelevant file contents, failed attempts, and detours. This degrades performance. A few commands keep the context clean:

/clear
Wipes the entire context. Use between unrelated tasks.
/compact
Summarises history into key decisions and file states. Frees space without losing progress.
/compact focus on API changes
Directed compact — tells Claude what to preserve.
Esc + Esc or /rewind
Opens the rewind menu. Restore conversation, code, or both to any earlier checkpoint.
/btw what does X do?
Side-question — answer shown as overlay, never enters context history.
claude --continue
Pick up the most recent session. Use --resume to choose from a list.
⚠️ Warning: If you've corrected Claude more than twice on the same issue, the context is polluted with failed approaches. Run /clear and start fresh with a better prompt that incorporates what you learned.

6. Use subagents for investigation

When Claude needs to explore a lot of files to answer a question, those reads consume your context. Subagents run in a separate context window, explore, and then report back a summary — leaving your main conversation clean.

# Instead of reading dozens of files in your main session...
$claude "Use subagents to investigate how our auth system
handles token refresh. Report back with a summary.
I want to know what utilities already exist."
✓ Subagent explored 12 files and returned a 200-token summary
Your main context grew by 200 tokens, not 12,000

You can also use subagents for verification after implementation: use a subagent to review this code for edge cases. A fresh context means no bias toward code it just wrote.

7. Run parallel sessions to multiply output

Claude Code scales horizontally. Once you're comfortable with one session, run multiple in parallel for faster delivery or independent review.

🌲
Worktrees
Separate CLI sessions in isolated git checkouts — edits don't collide.
🖥️
Desktop app
Manage multiple local sessions visually, each in its own worktree.
☁️
Claude Code on the web
Sessions on cloud infrastructure in isolated VMs — no local setup.
🤝
Agent teams
Multiple sessions with shared tasks, messaging, and a team lead agent.

A useful pattern is Writer / Reviewer: one session implements, another reviews with fresh context. Claude won't be biased toward code it wrote.

Session A — Writer
Implement a rate limiter for our API endpoints
Session B — Reviewer
Review the rate limiter in @src/middleware/rateLimiter.ts. Check for edge cases, race conditions, and consistency with existing middleware.

8. Automate with non-interactive mode

Use claude -p "prompt" in CI pipelines, pre-commit hooks, or scripts to run Claude without a session. The --output-format flag controls how output is structured for programmatic use.

# One-off query
claude -p "Explain what this project does"

# Structured output for scripts
claude -p "List all API endpoints" --output-format json

# Batch file migration
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

# Run autonomously with safety checks
claude --permission-mode auto -p "fix all lint errors"
💡 Tip: Scope --allowedTools tightly in batch scripts — it restricts what Claude can do when running unattended. Test on 2-3 files before running at scale.

9. Configure permissions to reduce interruptions

By default Claude asks before every file write or command. After the tenth click-through you stop reviewing. Three tools reduce this:

🤖
Auto mode
A classifier reviews each command and blocks only risky actions (scope escalation, unknown infrastructure). Safe work proceeds without prompts.
--permission-mode auto
📋
Permission allowlists
Permit specific commands you trust, like npm run lint or git commit. Configured with /permissions.
/permissions
🏖️
Sandboxing
OS-level isolation that restricts filesystem and network access. Claude works freely within the boundaries you set.
/sandbox

10. Avoid common failure patterns

⚠️ The kitchen-sink session
Symptom: You start with one task, ask something unrelated, loop back. Context is full of noise.
Fix: Run /clear between unrelated tasks. Keep each session focused on one workstream.
⚠️ Correcting over and over
Symptom: Claude keeps repeating the same mistake despite your corrections. Context is polluted with failed approaches.
Fix: After two failed corrections, /clear and write a sharper prompt that incorporates what you learned.
⚠️ The bloated CLAUDE.md
Symptom: Claude ignores specific instructions because they get lost in a long file.
Fix: Ruthlessly prune. If Claude already does something without the instruction, delete it. Convert recurring needs to hooks.
⚠️ No verification criteria
Symptom: Claude produces plausible-looking code that doesn't handle edge cases. You only find out later.
Fix: Always provide tests, a lint script, or a screenshot comparison. If you can't verify it, don't ship it.
⚠️ Infinite exploration
Symptom: You ask Claude to 'investigate' something vague. It reads hundreds of files and fills the context.
Fix: Scope investigations narrowly, or use subagents so exploration doesn't consume your main context.

Quick Reference

PracticeKey action
Provide verificationAdd test cases or a script to every implementation request
Explore before codingSwitch to plan mode first; press Ctrl+G to edit the plan
Write specific promptsName files, describe symptoms, define what 'done' looks like
Maintain CLAUDE.mdRun /init to generate; prune aggressively; commit to git
Reset context between tasks/clear after each unrelated workstream
Summarise long sessions/compact or /compact <focus instructions>
Investigate without pollutingUse subagents — they run in a separate context window
Reduce permission prompts--permission-mode auto or /permissions allowlists
Parallelize workWorktrees, Desktop app, or Claude Code on the web
Recover from mistakesEsc + Esc to open /rewind — restore code and/or conversation

What's Next

You've completed the Claude Code module. The next module covers Claude Skills — reusable instruction files that give Claude a consistent way of working.