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
Read Before Edit: Claude Code always reads a file before editing it. This ensures it understands the existing code and context, leading to more accurate edits. The Edit tool works by finding an exact string match in the file and replacing it with new text.

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 Code Session
Claude > Add try-catch error handling to the fetchUser function in src/api/users.ts

Before:

TypeScript
async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  const data = await response.json();
  return data;
}

After:

TypeScript
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 Code Session
Claude > Rename the function "getUserData" to "fetchUserProfile" everywhere
         in the codebase, including all imports and call sites

Claude Code will:

  1. Search for all occurrences using Grep to find every file that references getUserData
  2. Read each affected file to understand the context and imports
  3. Edit the function definition in the source file
  4. Update all imports in files that import the function
  5. Update all call sites where the function is called

Example: Extracting a Component

Claude Code Session
Claude > Extract the user avatar section from UserProfile.tsx into its
         own UserAvatar component. Create the new file and update imports.
Multi-File Tips: When asking for multi-file changes, be explicit about what you want. Mention the files involved, the scope of the change, and whether you want imports updated. Claude Code will handle the coordination, but clear instructions lead to better results.

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.

Claude Code Session
# 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.
Style Matching: Claude Code analyzes your existing code to match conventions. It picks up on your project's coding style, import patterns, naming conventions, and file structure. Mentioning "use the same patterns as existing files" reinforces this behavior.

Code Generation from Descriptions

You can describe functionality in plain English and let Claude Code generate the implementation:

Claude Code Session
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 Code Output
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
Review Carefully: Take a moment to review each proposed edit. Check that:
  • 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 Code Session
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 Code Session
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.

Always Use Version Control: Always work in a git repository when using Claude Code. This gives you a safety net — you can always 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 Code Session
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 Code Session
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 Code Session
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:

  1. Pick any file in your project and ask Claude to add JSDoc comments to all exported functions
  2. Ask Claude to create a new utility file with helper functions related to your project
  3. Try a multi-file refactoring: rename a function and update all references
  4. Ask Claude to add input validation to a function, then review the proposed edit carefully