Code Modification
Claude Code provides powerful code modification capabilities to help you quickly and accurately modify code. Understanding how to effectively guide Claude through code modifications is key to improving development efficiency.
Basic Principles of Code Modification
Clarity Over Ambiguity
Express your intent clearly:
❌ Bad approach:
Improve this function✅ Good approach:
Convert this function to async, add error handling, and wrap database calls with try-catchProvide Sufficient Context
Let Claude understand the reason and impact of the modification:
This component currently has display issues on mobile. Need to add responsive styles,
change to vertical layout on small screens. Reference the Header component's implementation.One Focus at a Time
Avoid mixing multiple unrelated modifications in a single request:
❌ Bad approach:
Refactor this file, add type definitions, fix bugs, optimize performance, update documentation✅ Good approach:
First add TypeScript type definitionsThen in the next step:
Now fix the null pointer bug on line 45Small Modifications
Single Line or Few Line Changes
For simple modifications, just describe them directly:
Change the timeout on line 23 from 3000 to 5000Add form validation at the beginning of the handleSubmit functionAdding Import Statements
Add an import for lodash's debounce functionModifying Configuration Values
Enable SWC minify in next.config.jsMedium Modifications
Function Refactoring
Provide clear refactoring goals:
Refactor the processUserData function:
1. Extract validation logic into a separate function
2. Replace Promise chains with async/await
3. Add detailed error messagesAdding New Features
Describe the feature requirements and implementation approach:
Add avatar upload functionality to the UserProfile component:
- Use react-dropzone for file uploads
- Limit file size to 5MB
- Support jpg, png formats
- Show preview before uploadError Handling Improvements
Improve error handling for API calls:
- Distinguish between network errors and business errors
- Add retry logic (max 3 retries)
- Display user-friendly error messagesLarge Modifications
Component Refactoring
For large refactoring, proceed step by step:
Step 1: Break the Dashboard component into smaller sub-components
First list the suggested component structureAfter reviewing the structure:
OK, start refactoring according to this structure, first create the DashboardHeader componentArchitecture Changes
Migrate state management from Redux to Zustand:
1. First create Zustand store definitions
2. I'll review before continuing to migrate componentsAPI Refactoring
Refactor REST API to GraphQL:
1. First design the GraphQL schema
2. Then implement the resolvers
3. Finally update client queriesCode Modification Patterns
Add Pattern
Add loading state to the Button component:
- Add isLoading prop
- Show spinner when loading
- Disable button when loadingRemove Pattern
Remove all code related to the old authentication system:
- Delete the src/auth/legacy/ directory
- Remove old methods from AuthContext
- Clean up related type definitionsReplace Pattern
Replace all moment.js usage with date-fns:
1. First list all places using moment
2. Replace each with equivalent date-fns functionsExtract Pattern
Extract reusable logic from UserDashboard:
- Extract data fetching logic into custom hook
- Extract formatting functions into utils
- Extract constants into a separate fileHandling Dependencies
Identifying Impact Scope
If we modify the User interface, which files would be affected?Cascade Updates
Update the User interface to add an email field, then update all affected filesBackward Compatibility
Add a new API endpoint, but maintain compatibility with the old endpoint, add deprecation warningCode Style and Standards
Follow Project Standards
Refactor this file according to the project's ESLint rulesUnify Code Style
Unify the code style of this file to:
- Use single quotes
- 2 space indentation
- Trailing commasNaming Conventions
Change all variable names to camelCase, function names starting with verbsTest-Driven Modifications
Write Tests First
Write test cases for the calculateDiscount function,
then modify the implementation based on the testsPost-Modification Verification
After completing modifications, run tests and fix any failing casesAdd Boundary Tests
Add tests for edge cases of this function:
- Empty input
- Extremely large values
- Negative numbers
- Special charactersPerformance Optimization Modifications
Identify Bottlenecks
Analyze this component's performance issues and suggest optimization approachesImplement Optimizations
Optimize the ProductList component:
- Use React.memo to avoid unnecessary re-renders
- Implement virtual scrolling
- Lazy load imagesVerify Improvements
Add performance monitoring code to measure the difference before and after optimizationSecurity Modifications
Fix Security Vulnerabilities
Fix XSS vulnerability:
- Escape user input
- Use DOMPurify to sanitize HTML
- Add CSP headersStrengthen Validation
Strengthen input validation:
- Add server-side validation
- Use Zod for type-safe validation
- Add rate limitingIncremental Modification Strategy
Small Steps
Refactor this 500-line file, modifying one function at a time,
I'll test after each modification before continuingFeature Flags
Add the new feature, but control it with a feature flag,
disabled by default until testing is completeParallel Versions
Create a new version of the API endpoint (v2), keep v1 unchangedCode Review and Iteration
Request Review
Here's my modification plan, please review and suggest improvementsIterative Improvement
Based on your suggestions, I want to adjust the error handling part,
using more fine-grained error typesFinal Check
Modifications complete, please check:
1. Are there any missed edge cases
2. Is error handling complete
3. Does the code follow best practicesDocumentation Sync
Update Comments
After modifying the function signature, sync the JSDoc commentsUpdate README
After adding the new feature, update the README's feature list and usage examplesUpdate Type Definitions
After modifying the API response format, update the TypeScript type definitionsCommon Pitfalls and Solutions
Pitfall 1: Modification Scope Too Large
Problem: Modifying too much code at once, difficult to debug
Solution: Break into small steps, verify each step
Pitfall 2: Ignoring Side Effects
Problem: Modifying one piece of code breaks other functionality
Solution: Analyze dependencies first, create a complete modification plan
Pitfall 3: Inconsistent Style
Problem: New code is inconsistent with existing code style
Solution: Explicitly specify the code standards to follow
Pitfall 4: Missing Tests
Problem: No verification of correctness after modification
Solution: Run tests before and after modifications, add new tests when necessary
Best Practices Checklist
- [ ] Clearly describe modification intent and reason
- [ ] Provide sufficient context information
- [ ] Focus on one major modification at a time
- [ ] Consider the modification's impact scope
- [ ] Follow the project's code standards
- [ ] Maintain backward compatibility (if applicable)
- [ ] Update related tests
- [ ] Sync documentation and comments
- [ ] Verify the correctness of modifications
- [ ] Consider performance and security implications
By following these principles and patterns, you can use Claude Code for code modifications more effectively, improving code quality and development efficiency.