Anthropic releases the Claude Code Smart Programming Best Practices Guide (Chinese version).
Claude Code is a command-line tool for agile coding. This article covers proven techniques and methods for using Claude Code across various codebases, languages, and environments. We most...
Claude Code is used inintelligentCommand-line tools for agency coding. This article covers proven techniques and methods for using them across various codebases, languages, and environments.Claude Code.
We recently releasedClaude CodeThis is forintelligentA command-line tool for coding. Developed as part of a research project.Claude Code provides Anthropic engineers and researchers with a more native way to...ClaudeIntegrate it into their coding workflow.
Claude The code is intentionally designed to be low-level and non-mandatory, providing access close to the original model without imposing a specific workflow. This design philosophy creates a flexible, customizable, scriptable, and secure system.powerfulTools. Although functionspowerfulHowever, this flexibility is not ideal for first-time users.intelligentThere is a learning curve for engineers of coding tools—at least until they develop their own best practices.
This article outlines proven, universal patterns applicable both within the Anthropic team and across various codebases, languages, and environments.Claude External engineers at Code. Nothing in this list is set in stone or universally applicable; consider these suggestions as a starting point. We encourage you to experiment and find what works best for you!
Looking for more detailed information? We are atclaude.ai/codeThe full documentation covers all the features mentioned in this article and provides additional examples, implementation details, and advanced techniques.
1. Customize your settings
Claude Code is aintelligentCoding assistant, willautomaticExtract the context into the hint. This context collection is time-consuming and requires tokens, but you can optimize it through environment tuning.
a. Create the CLAUDE.md file
CLAUDE.md is a special file.ClaudeWhen starting a conversationautomaticExtract it into the context. This makes it an ideal location for recording the following:
- Commonly used bash commands.
- Core documents andpracticalFunction.
- Code style guidelines.
- Test instructions.
- Repository conventions (such as branch naming, merging, and rebasing).
- Development environment setup (e.g., pyenv usage, available compilers).
- Any unexpected behavior or warnings specific to the project.
- You wishClaudeOther information to remember.
There are no fixed format requirements for the CLAUDE.md file. We recommend keeping it concise and easy to read. For example:
You can place the CLAUDE.md file in multiple locations:
- Repository root directoryOr wherever you run claude (most common usage). Name it CLAUDE.md and commit it to git for sharing across sessions and teams.recommendAlternatively, you can name it CLAUDE.local.md and ignore it via .gitignore.
- Any parent directory of the directory where you run claudeThis is particularly useful for monorepo, for example, you might run claude from root/foo, and there are files in both root/CLAUDE.md and root/foo/CLAUDE.md. Both will...automaticExtracted into context
- You can run any subdirectory of the directory containing claude.This is the opposite of the situation described above, where you are working with files in a subdirectory.ClaudeIt will extract the CLAUDE.md file from the subdirectory as needed.
- Your home directory(~/.claude/CLAUDE.md). This will apply to all your Claude sessions when you run the /init command.ClaudemeetingautomaticThis will generate a CLAUDE.md file for you.
b. Adjust your CLAUDE.md file
Your CLAUDE.md file will becomeClaudePrompt wordsIt is part of, and therefore should be like any frequently usedPrompt wordsOptimize accordingly. A common mistake is adding a lot of content without iterating on its effectiveness. Take the time to experiment and determine how to make the model best follow the instructions.
You can manually add content to CLAUDE.md, or press the # key to specify it.ClaudeOne instruction, itautomaticMerge it into the relevant CLAUDE.md. Many engineers frequently use # to record commands, documents, and style guidelines while coding, and then include changes to CLAUDE.md in the commit so that team members can also benefit.
In Anthropic, we occasionally pass throughTip ImproverRun the CLAUDE.md file and frequently adjust the instructions (e.g., add emphasis with "important" or "must") to improve compliance.
c. ManagementClaudeList of tools allowed
By default,Claude Code requests permissions for any operation that might modify the system: file writing, most bash commands, MCP tools, etc. We intentionally adopted this conservative design to prioritize security. You can customize the allowed list to add tools you've verified are safe, or allow potentially insecure operations that are easily reversible (such as file editing and git commits).
There are four ways to manage and allow tools:
- When prompted during the session, select "Always Allow".
- start upClaude After coding, use the `/allowed-tools` command to add or remove tools from the allowed list. For example:
- Add Edit to always allow file editing.
- Add Bash(git commit:*) to allow git commits.
- Add `mcp__puppeteer__puppeteer_navigate` to allow navigation using the Puppeteer MCP server.
- Manually edit the .claude/settings.json or ~/.claude.json file (it is recommended to include the former in version control for team sharing).
- Use the `--allowedTools` command-line parameter to set session-specific permissions.
d. If using GitHub, please install the gh CLI. Claude
Know how to use the gh CLI to interact with GitHub, including creating issues, submitting pull requests, and reading comments. If gh is not installed...ClaudeInteraction can still be achieved via the GitHub API or the installed MCP server.
2. ForClaudeProvide more tools
ClaudeIt has access to your shell environment, which you can build a set of convenient scripts and functions for as if it were your own. It can also leverage more sophisticated tools through the MCP and REST APIs.
a. willClaudeUse in conjunction with bash tools
Claude Code inherits from your bash environment, giving it access to all your tools. AlthoughClaudeKnow the commonpracticalPrograms like Unix tools and gh, but without instructions, it won't know about your custom bash tools:
- 1. TellClaudeTool name and usage examples.
- 2. LetClaudeRun `--help` to view the tool documentation.
- 3. Record commonly used tools in CLAUDE.md.
b.ClaudeUsed in conjunction with MCP
Claude Code can function as both an MCP server and a client. As a client, it can connect to any number of MCP servers to access their tools in three ways:
- In the project configuration (run in this directory)Claude (Available when coding).
- In the global configuration (available in all projects).
- In the committed .mcp.json file (available to anyone in the codebase). For example, you can add Puppeteer and Sentry servers to your .mcp.json so that every engineer working in your repository can use these tools out of the box. When using MCP, start it with the --mcp-debug flag.ClaudeIt also helps identify configuration problems.
c. Using the custom forward slash command
For repetitive workflows—debugging loops, log analysis, etc.—store prompt templates in Markdown files within the `.claude/commands` folder. These commands will appear in the forward slash command menu when you type `/`. You can commit these commands to Git to make them available to other members of the team.
Custom forward slash commands can include the special keyword $ARGUMENTS to pass parameters from command calls.
For example, here is a forward slash command that you can useautomaticPull and fix GitHub issues:
Place the above content into the .claude/commands/fix-github-issue.md file, and it will be available in [the relevant section].Claude Use the `/project:fix-github-issue` command in the code. For example, you can use `/project:fix-github-issue 1234` to...ClaudeFixed issue #1234. Similarly, you can add your personal commands to the ~/.claude/commands folder to make them available in all sessions.
3. Try common workflows
Claude Code does not enforce a specific workflow; you can use it flexibly as needed. This flexibility has fostered several user communities.High efficiencyuseClaude The success pattern of code:
a. Explore, plan, code, submit
This versatile workflow is suitable for many problems:
- letClaudeWhen reading relevant files, images, or URLs, you can provide general guidance ("read the file for processing logs") or specific filenames ("read logging.py"), but explicitly tell it not to write any code yet. This is a part of the workflow where you should consider using sub-agents extensively, especially for complex problems.
- TellClaudeUsing sub-agents to verify details or investigate potential specific issues, especially in the early stages of a conversation or task, helps maintain contextual availability without incurring a significant loss in efficiency.ClaudeDevelop a plan to solve a specific problem. We suggest using the word "think" to trigger expanded thinking patterns, which will give...ClaudeMore computation time allows for a more thorough evaluation of alternatives. These specific phrases directly correspond to progressively increasing levels of thinking budget in the system: "think" < "think hard" < "think harder" < "ultrathink". Each level allocates more thinking budget to Claude. If the results of this step seem reasonable, you can have Claude create a document or GitHub issue to document its plans so you can revert to this point if the implementation (step 3) doesn't meet your requirements.
- letClaudeImplement its solution in code. This is also a good time to require it to explicitly validate the rationale behind its solution as it implements each part of the solution.
- letClaudeSubmit the results and create a pull request. If relevant, this is also a good time to...ClaudeUpdate any README or changelog to explain what it just did.
Steps 1 and 2 are crucial—without them,ClaudeThey often jump straight to writing the solution code. While this is exactly what you want, it...ClaudeConducting research and planning beforehand can significantly improve the performance of in-depth thinking about problems.
b. Write tests and submit; code, iterate, and submit.
This is Anthropic's favorite workflow, suitable for changes that can be easily verified through unit tests, integration tests, or end-to-end tests. Test-Driven Development (TDD) in...intelligentIn coding, it becomes morepowerful:
- letClaudeWrite tests based on the expected inputs/outputs. Explicitly state that you are conducting test-driven development so that it avoids creating mock implementations, even for features that don't yet exist in the codebase.
- TellClaudeRun the tests and confirm they do not fail. It's often helpful to explicitly tell it not to write any implementation code at this stage. Once you are satisfied with the tests, let...ClaudeSubmit the test. LetClaudeWrite code that passes the tests and instruct it not to modify the tests.
- TellClaudeContinue until all tests pass. This usually requires several iterations.ClaudeOnly then can you write code, run tests, tweak the code, and run tests again. At this stage, requiring it to use independent sub-proxies to verify whether the implementation is overfitting might be helpful.
- letClaudeSubmit your code when you are satisfied with the changes.
whenClaudeIt performs better when there's a clear goal for iteration. This goal could be a visual sketch, a test case, or any specific objective. This means that if there's a clear goal or direction,ClaudeTo better realize its potential and deliver better results or solutions
c. Write code, take screenshots, and iterate.
Similar to the testing workflow, you can...ClaudeProvide visual targets:
- forClaudeProvide a method for capturing browser screenshots (e.g., using Puppeteer MCP, iOS simulator MCP server, or manually copying/pasting the screenshot to...).Claudemiddle).
- By copying/pasting or dragging and dropping images, or by givingClaudeImage file path, forClaudeProvide a visual simulation.
- letClaudeImplement the design using code, capture screenshots of the results, and iterate until the results match the simulation.
- When you are satisfied, letClaudesubmit.
Like humans,ClaudeThe output improves significantly after iterations. While the first version may be good, it is usually much better after 2-3 iterations.ClaudeProvide tools to view its output for optimal results.
d. YOLO Safe Mode
You can use claude –dangerously-skip-permissions to bypass all permission checks, allowingClaudeWork undisturbed until completion, without supervision. This approach is particularly suitable for workflows such as fixing lint bugs or generating boilerplate code.
However, please note that it is allowed.ClaudeRunning arbitrary commands carries risks that could lead to data loss, system corruption, or even data breaches (e.g., via injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in containers that are not connected to the network. You can refer to this guide on developing containers using Docker.Implementation Plan.
e. Codebase Q&A
When working with a new codebase, you can useClaude Learn and explore Code. You can...ClaudeAsk the same questions you would ask other engineers on the project when pair programming.ClaudeIt can proactively search code repositories to answer general questions such as:
- How does a logging system work?
- How do I create a new API endpoint?
- What does the `async move{…}` line on line 134 of the `foo.rs` file do?
- What boundary cases does CustomerOnboardingFlowImpl handle?
- Why is foo() called on line 333 instead of bar()?
- What is the Java equivalent implementation of line 334 in baz.py?
In Anthropic, it is used in this way Claude Code has become a core part of our onboarding process, significantly shortening the adaptation time for new employees and reducing the workload of other engineers. No special prompts needed! Just ask questions.Claude They will then explore the code to find the answer.
f. UseClaudePerform Git operations
ClaudeableHigh efficiencyHandles various Git operations. Many Anthropic engineers use it for over 90% of their Git interactions.Claude:
- Search Git history to answer questions such as "What changes were included in version 1.2.3?", "Who is responsible for this specific feature?", or "Why is this API designed this way?". Provide explicit hints.ClaudeChecking the git history can be very helpful in answering these types of queries.
- Write the submission message.ClaudemeetingautomaticReview your changes and recent history, and consider all relevant context when writing your commit message.
- Handle complex Git operations, such as restoring files, resolving rebase conflicts, comparing and porting patches, etc.
g. UseClaudeInteracting with GitHub
Claude Code can manage various GitHub interactions:
- Create a pull request.ClaudeUnderstanding the abbreviation "pr" will help generate appropriate commit messages based on the diff and surrounding context.
- accomplishSimpleOne-time fix for code review comments: Simply tell it to fix the comments on the PR (optionally provide more specific instructions), and it will push back to the PR branch when finished.
- Fix failed builds or linter warnings.
- By lettingClaudeIterate through unresolved issues on GitHub to categorize and filter them.
This eliminates the need to memorize the gh command-line syntax, and...automaticIt transformed routine tasks.
h. UseClaudeProcessing Jupyter Notebooks
Anthropic researchers and data scientists useClaude Code read and write Jupyter notebooks.ClaudeIt can interpret output, including images, providing a shortcut for data exploration and interaction. While there are no mandatory prompts or workflows, we...recommendThe workflow is to open in VS CodeClaude Code and .ipynb files.
You can also letClaudeClean or beautify your Jupyter notebook before showing it to colleagues. Specifically telling it to make the notebook or its data visualizations "look good" helps remind it that this is about optimizing the human viewing experience.
4. Optimize your workflow
The following recommendations apply to all workflows:
a. Instructions must be specific and clear.
Claude The success rate of code increases significantly with the specificity of the instructions, especially on the first attempt. Providing clear instructions in advance reduces the need for subsequent corrections.
ClaudeIt can infer intent, but cannot read thought. Explicit instructions lead to better alignment with expectations.
b. forClaudeProvide images
ClaudeThe following methods can be used to process images and charts effectively:
- Paste the screenshot directly (Pro tip: On macOS, press cmd+ctrl+shift+4 to save the screenshot to the clipboard, then press ctrl+v to paste. Note that this is not the commonly used cmd+v pasting method on Mac, and it is not available for remote operations).
- Drag the image directly to the prompt input box.
- Provide the image file path.
This is particularly useful in scenarios where design drafts serve as a reference standard for UI development, and in using visual charts for analysis and debugging. Even without adding visual elements to the context, explicitly informing...ClaudeThe visual appeal of the final result remains a significant factor.
c. Explicitly specify the needClaudeFiles to view or process
Use the Tab keyautomaticautocomplete functionfastReferencing any file or folder in the codebase helpsClaudeAccurately locate or update target resources.
d. forClaudeProvide URL link
existPrompt wordsPaste a specific URL into the text.ClaudeWillautomaticGet and read the content. To avoid repeatedly requesting permissions for the same domain (such as docs.foo.com), you can use the /allowed-tools command to add the domain to the allowed list.
e. Timely correction and frequent adjustment
AlthoughautomaticAccept mode (switchable via shift+tab) allowsClaudeWorking independently, but guided through proactive collaboration.ClaudeThis usually yields better results. Best practice is to provide guidance at the beginning of the task.ClaudePlease provide a complete description of your requirements, but you can also make the following modifications at any time:
Four core correction tools:
- advance planning:RequireClaudeFirst, develop a plan and clearly instruct that coding should not begin without confirmation.
- Immediate interruption (press Esc key): can beClaudePause the current operation while thinking, calling tools, or editing files to preserve the context so you can adjust your instructions.
- Rewind history (double-click the Esc key): Go back to a previous point in time and modify the previous prompts to explore different options.
- Cancel the changeIt is often used in conjunction with item 2, requiringClaudeUndo the changes and try a new approach.
AlthoughClaude Code may occasionally solve a problem perfectly on the first try, but using these fixes usually leads to a better solution faster.
f. Use /clear to maintain context focus
During long conversations,ClaudeThe context window can accumulate irrelevant dialogs, file content, and commands, thus impacting performance or causing distraction. It is recommended to frequently use the `/clear` command to reset the context window between different tasks.
g. Use checklists and draft boards to handle complex workflows.
For multi-step tasks or scenarios requiring detailed solutions (such as code migration, fixing numerous lint errors, or running complex build scripts), this can be achieved by allowing...ClaudeUse Markdown files (or even GitHub issues!) as checklists and work drafts to improve productivity:
For example, when fixing a large number of lint issues, you can do the following:
- 1. LetClaudeRun the lint command and write all errors (including filenames and line numbers) to a Markdown checklist.
- 2. GuidanceClaudeAddress each issue one by one, marking it as complete after repair and verification before moving on to the next item.
h. TowardsClaudeTransmitting data
There are several ways to...ClaudeProvide data:
- Copy and paste directly into the prompt (the most common method).
- Input through pipeClaude Code (e.g., cat foo.txt | claude) is particularly suitable for logs, CSVs, and big data.
- TellClaudeObtain data using bash commands, the MCP tool, or custom forward slash commands.
- letClaudeReading files or retrieving URLs (also works for images) are methods that are used in combination in most sessions. For example, you can pipe input to a log file and then let...ClaudeUse tools to obtain additional context for debugging logs.
5. Use headless modeautomaticInfrastructure
Claude Code includesHeadless modeSuitable for CI, pre-commit hooks, build scripts, andautomaticFor non-interactive scenarios such as programming. Use the -p flag and prompt to enable headless mode, and use --output-format stream-json to get streaming JSON output.
Please note that headless mode does not persist between sessions. You must trigger it in each session.
a. UseClaudeClassify the problems
Headless mode can be triggered by GitHub events.automaticThis includes things like creating new issues in your repository. For example, public...Claude Code repositoryuseClaudeWhen new problems arise, examine them and assign them appropriate labels.
b. UseClaudeAs a linter
Claude Code can provide detection capabilities beyond those of traditional lint tools.Subjective code reviewIt can identify problems such as spelling errors, outdated comments, and misleading function or variable names.
6. Through multipleClaudeWorkflow upgrade
Besides being used alone, some of the mostpowerfulApplication scenarios involve running multiple parallel processesClaudeExample:
a. Let oneClaudeWrite code, anotherClaudeverify
oneSimpleBut the effective method is to let aClaudeWrite code while another reviews or tests it. Similar to collaborating with multiple engineers, sometimes maintaining an independent context is beneficial:
useClaudeWrite code to run /clear or launch a second terminal from another terminal.Claude Let the second oneClaudeReview the firstClaudeStart another jobClaude(Or again /clear) to read the code and review feedback.ClaudeModify the code based on feedback. You can do something similar with tests: let aClaudeWrite a test, then let another oneClaudeWrite code to make the tests pass. You can even make your...ClaudeThe instances communicate with each other by giving them separate worksheets and telling them which ones to write to and which ones to read from.
This separation is usually more effective than letting a singleClaudeHandling everything leads to better results.
b. Create multiple checkouts from the repository
Many engineers at Anthropic are not waitingClaudeInstead of completing each step, do this:
- Create 3-4 git checkouts in separate folders.
- Open each folder in each terminal tab.
- Start in each folderClaudePerform different tasks.
- It continuously checks the progress and approves/denies permission requests.
c. Using git worktree
This approach works for multiple independent tasks, providing a more lightweight alternative to multiple checkouts. Git worktrees allow you to check out multiple branches of the same repository into separate directories. Each worktree has its own working directory and isolated files, while sharing the same Git history and reflog.
Using git worktree allows you to run multiple [projects] simultaneously in different parts of your project.ClaudeEach session focuses on its own independent task. For example, you might let a...ClaudeRefactor your authentication system, while another builds a completely unrelated data visualization component. Because the tasks do not overlap, each...ClaudeBoth can work at full speed without waiting for changes from the other or handling merge conflicts:
- Create a working tree:git worktree add ../project-feature-a feature-a.
- Start in each worktreeClaude:cd ../project-feature-a && claude.
- Create additional worktrees as needed.Repeat steps 1-2 in the new terminal tab.
- Use consistent naming conventions.
- Each worktree maintains one terminal tab.
- If you are using iTerm2 on your Mac, set notifications when...ClaudeWhen attention is needed.
- Use separate IDE windows for different worktrees.
- Clean up after completion: git worktree remove ../project-feature-a.
d. Combine headless mode with custom tools
claude -p (headless mode) programmatically...Claude Code integrates into larger workflows, leveraging its built-in tools and system hints. There are two main modes for using headless mode:
- 1. Distributed processing is suitable for large-scale migration or analysis.(For example, analyzing the sentiment of hundreds of logs or analyzing thousands of CSV files):
- letClaudeWrite a script to generate a list of tasks. For example, generate a list of 2,000 files that need to be migrated from framework A to framework B.
- Process tasks in a loop, calling the function programmatically for each task.ClaudeGive it a task and a set of tools you can use. For example: `claude -p "migrate foo.py from React to Vue. Upon completion, it must return the string 'OK' if successful, and 'F' if it fails."AIL. "--allowedTools Edit Bash(git commit:*)"
- Run the script multiple times and refine your prompts to achieve the desired results.
- Call `claude -p "<your prompt>" –json | your_command`, where `your_command` is the next step in your pipeline. That's it!
- JSON output can help provide structure for...automaticChemical treatment.
For both of these use cases, use the `--verbose` flag for debugging.ClaudeCalling it might be helpful. We generally recommend turning off verbose mode in production environments for clearer output.
Written by Boris Cherny. This work draws on the entire...Claude The best practices, creative methods, and workflows of the Code user community constantly inspire us. Special thanks also to Daisy Hollman, Ashwin Bhat, Cat Wu, Sid Bidasaria, Cal Rueb, Nodir Turakulov, Barry Zhang, Drew Hodun, and many other Anthropic engineers for their contributions.Claude Code's valuable insights and practical experience helped shape these recommendations.
Original linkhttps://www.anthropic.com/engineering/claude-code-best-practices
OpenAIConstruction Agents practicalGuide (PDF file) - AITutorial materials
How to generate a mini-program using Trae, and test MCP.AgentContext and other functions