Course navigation
Claude CodeLesson 25 of 25

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.

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 here flows from this one constraint: manage context carefully, keep prompts focused, and reset often.

1. Always give Claude a way to verify its work

This is the single most impactful 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, you become the only feedback loop.

Instead of…Try…
implement a function that validates email addresseswrite a validateEmail function. example test cases: user@example.com → true, invalid → false. run the tests after implementing
make the dashboard look better[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them
the build is failingthe 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.

PhaseModeWhat to doExample prompt
Exploreplan modeRead files and answer questions without making changes.read /src/auth and understand how sessions and login work. also look at how environment variables are managed.
Planplan modeGet a detailed plan. Press Ctrl+G to edit it before coding starts.I want to add Google OAuth. What files need to change? What's the session flow? Create a plan.
Implementdefault modeCode against the plan and verify with tests.implement the OAuth flow from your plan. write tests for the callback handler, run the suite and fix any failures.
Commitdefault modeCommit with a descriptive message and open a PR.commit with a descriptive message and open a PR
Skip the plan for small, obvious tasks — fixing a typo, adding a log line, renaming a variable. 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. Reference files, mention constraints, and point to examples.

Instead of…Try…
add tests for foo.pywrite a test for foo.py covering the edge case where the user is logged out. avoid mocks.
fix the login bugusers report login fails after session timeout. check src/auth/, especially token refresh. write a failing test that reproduces it, then fix it
add a calendar widgetlook at HotDogWidget.php to understand the widget pattern. follow it to build a calendar widget: pick a month, paginate year. no new libraries

You can also provide rich input: use @filename to reference files directly, paste screenshots, 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.

IncludeSkip
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'
Check CLAUDE.md into git so your whole team benefits. 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:

CommandWhat it does
/clearWipes the entire context. Use between unrelated tasks.
/compactSummarises history into key decisions and file states. Frees space without losing progress.
/compact focus on API changesDirected compact — tells Claude what to preserve.
Esc + Esc or /rewindRestore conversation, code, or both to any earlier checkpoint.
/btw what does X do?Side-question — answer shown as overlay, never enters context history.
claude --continuePick up the most recent session. Use --resume to choose from a list.
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.

ApproachDescription
WorktreesSeparate CLI sessions in isolated git checkouts — edits don't collide.
Desktop appManage multiple local sessions visually, each in its own worktree.
Claude Code on the webSessions on cloud infrastructure in isolated VMs — no local setup.
Agent teamsMultiple sessions with shared tasks, messaging, and a team lead agent.

Writer / reviewer pattern

SessionPrompt
WriterImplement a rate limiter for our API endpoints
ReviewerReview 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

# Unattended run with safety checks
claude --permission-mode auto -p "fix all lint errors"
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:

ToolDescriptionCommand
Auto modeA classifier reviews each command and blocks only risky actions. Safe work proceeds without prompts.--permission-mode auto
Permission allowlistsPermit specific commands you trust, like npm run lint or git commit./permissions
SandboxingOS-level isolation that restricts filesystem and network access./sandbox

10. Avoid common failure patterns

PatternSymptomFix
The kitchen-sink sessionContext is full of noise from unrelated tasks.Run /clear between unrelated tasks. Keep each session focused on one workstream.
Correcting over and overClaude repeats the same mistake despite corrections.After two failed corrections, /clear and write a sharper prompt incorporating what you learned.
The bloated CLAUDE.mdClaude ignores specific instructions buried in a long file.Ruthlessly prune. Convert recurring needs to hooks.
No verification criteriaPlausible-looking code that doesn't handle edge cases.Always provide tests, a lint script, or a screenshot comparison.
Infinite explorationClaude reads hundreds of files and fills the context.Scope investigations narrowly, or use subagents.

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

Before you continue

  • Context is finite — verify work, stay specific, and reset often with /clear or /compact.
  • Explore and plan before coding on multi-file changes.
  • Keep CLAUDE.md lean; use subagents and parallel sessions for investigation and review.
  • Automate with claude -p; reduce permission friction with auto mode and allowlists.
  • Next module: Claude Skills — reusable instruction files for consistent workflows.

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.