Editing Code Intermediate
Claude Code's core strength is editing code intelligently. It can make precise, targeted changes to existing files, create new ones from scratch, and coordinate edits across your entire project. This lesson covers the editing tools, practical patterns, and how to review and control changes.
How Claude Code Edits Files
Claude Code uses three primary tools for file operations:
| Tool | What It Does | When It's Used |
|---|---|---|
| Read | Reads the full or partial contents of a file | Before editing, to understand the current code |
| Edit | Makes a targeted string replacement in a file | Modifying specific parts of existing files |
| Write | Creates a new file or overwrites an existing file completely | Creating new files or complete rewrites |
Single File Edits
The most common operation is editing a single file. Simply describe the change you want, and Claude will locate the right file, read it, and propose an edit.
Example: Adding Error Handling
Claude > Add try-catch error handling to the fetchUser function in src/api/users.ts
Before:
async function fetchUser(id: string): Promise<User> { const response = await fetch(`/api/users/${id}`); const data = await response.json(); return data; }
After:
async function fetchUser(id: string): Promise<User> { try { const response = await fetch(`/api/users/${id}`); if (!response.ok) { throw new Error(`Failed to fetch user: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error(`Error fetching user ${id}:`, error); throw error; } }
Multi-File Refactoring
Claude Code excels at changes that span multiple files. It can rename functions across the codebase, move code between files, update imports, and ensure consistency.
Example: Renaming a Function Across the Codebase
Claude > Rename the function "getUserData" to "fetchUserProfile" everywhere
in the codebase, including all imports and call sites
Claude Code will:
- Search for all occurrences using Grep to find every file that references
getUserData - Read each affected file to understand the context and imports
- Edit the function definition in the source file
- Update all imports in files that import the function
- Update all call sites where the function is called
Example: Extracting a Component
Claude > Extract the user avatar section from UserProfile.tsx into its
own UserAvatar component. Create the new file and update imports.
Creating New Files
Claude Code can create entirely new files from a description. It uses the Write tool to create files with appropriate content, structure, and conventions matching your project.
# Create a new utility file Claude > Create a new file src/utils/validation.ts with email, phone, and URL validation functions. Use the same patterns as the existing utils files. # Create a React component Claude > Create a new ErrorBoundary component in src/components/ErrorBoundary.tsx that catches rendering errors and shows a user-friendly fallback UI. # Create a test file Claude > Create a test file for the UserService class. Use Jest with the same patterns as existing test files in this project.
Code Generation from Descriptions
You can describe functionality in plain English and let Claude Code generate the implementation:
Claude > Create a REST API endpoint for managing blog posts.
It should support:
- GET /api/posts (list all, with pagination)
- GET /api/posts/:id (get single post)
- POST /api/posts (create new post)
- PUT /api/posts/:id (update existing)
- DELETE /api/posts/:id (delete post)
Use the same Express.js patterns as the existing routes.
Include input validation and error handling.
Claude Code will examine your existing routes to match your patterns, then create the route handler, any needed middleware, and type definitions.
Reviewing Changes Before Accepting
In the default permission mode, Claude Code shows you each edit before applying it. You get to review exactly what will change.
Claude wants to edit src/utils/helpers.ts Replace: function formatDate(date) { return date.toString(); } With: function formatDate(date: Date): string { return new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric', }).format(date); } Allow this edit? [y/n/e] y = yes, n = no, e = edit the change
- The right file is being edited
- The old code being replaced matches what you expect
- The new code looks correct and follows your style
- No unintended side effects are introduced
Undoing Changes
If Claude Code makes an edit you don't like, you have several options to undo it:
Option 1: Git Checkout (Recommended)
If you haven't committed the changes yet, use git to restore the file:
Claude > Undo the last edit to src/utils/helpers.ts using git checkout
Option 2: Ask Claude to Revert
Ask Claude directly to undo its changes:
Claude > That last edit was wrong. Revert src/utils/helpers.ts to its
previous state
Option 3: Reject During Review
The best approach is to reject an edit during the review step by pressing n when Claude asks for permission.
git diff to see what changed and git checkout to restore files. Consider committing or stashing your work before starting a large Claude Code session.
Practical Examples
Example 1: Adding TypeScript Types
Claude > Add TypeScript types to all functions in src/utils/helpers.ts.
The file currently uses plain JavaScript with no type annotations.
Example 2: Converting CSS to Tailwind
Claude > Convert the custom CSS classes in Header.tsx to Tailwind utility
classes. Remove the corresponding CSS from Header.css.
Example 3: Adding Logging
Claude > Add structured logging to all API route handlers in src/routes/.
Use the existing logger from src/utils/logger.ts. Log the request
method, path, status code, and response time.
Try It Yourself
Practice code editing with these exercises:
- Pick any file in your project and ask Claude to add JSDoc comments to all exported functions
- Ask Claude to create a new utility file with helper functions related to your project
- Try a multi-file refactoring: rename a function and update all references
- Ask Claude to add input validation to a function, then review the proposed edit carefully
Lilly Tech Systems