Ad Space (horizontal)
Use Cases

How to Automate Refactoring with Claude Code

Learn how to efficiently automate code refactoring using Claude Code. Includes practical prompts and concrete refactoring patterns for real-world projects.

Why Refactor with Claude Code?

Everyone knows refactoring is important, but it’s tedious to do manually and often gets deprioritized. Claude Code understands your entire project and can autonomously execute refactoring across multiple files.

Pattern 1: Improving Type Safety

Eliminating any Types

> Search the project for all any types and replace them with proper types.
> After the changes, verify that npx tsc --noEmit passes.

Here’s how Claude Code handles this:

  1. Searches for files containing any types
  2. Infers appropriate types from the surrounding code
  3. Creates type definition files if needed
  4. Runs the type checker to verify everything compiles

Before and After

// Before
function processData(data: any): any {
  return data.items.map((item: any) => item.name);
}

// After
interface DataPayload {
  items: Array<{ name: string; id: number }>;
}

function processData(data: DataPayload): string[] {
  return data.items.map((item) => item.name);
}

Pattern 2: Splitting Functions and Clarifying Responsibilities

Breaking up oversized functions is something Claude Code handles exceptionally well.

> The createOrder function in src/services/orderService.ts is over 200 lines.
> Split it into smaller functions following the single responsibility principle.
> Make sure existing tests still pass.

Prompt for Splitting

> Split the function using these guidelines:
> - Each function should be 30 lines or fewer
> - Separate validation, business logic, and persistence
> - Add JSDoc comments to each function
> - Split tests to match the new function boundaries

Pattern 3: Standardizing Error Handling

Unify error handling patterns across your entire project.

> Standardize error handling across the project:
> - Use a custom error class (AppError)
> - Define error codes as constants
> - Always include logging in try-catch blocks

Here’s an example of what Claude Code generates:

// src/errors/app-error.ts
export class AppError extends Error {
  constructor(
    public readonly code: string,
    message: string,
    public readonly statusCode: number = 500,
    public readonly cause?: Error
  ) {
    super(message);
    this.name = 'AppError';
  }
}

// Error code constants
export const ErrorCodes = {
  USER_NOT_FOUND: 'USER_NOT_FOUND',
  INVALID_INPUT: 'INVALID_INPUT',
  DB_CONNECTION_ERROR: 'DB_CONNECTION_ERROR',
} as const;

Pattern 4: Adding and Improving Tests

Add tests where coverage is lacking.

# Use coverage reports to guide test additions
npx vitest run --coverage | claude -p "Identify files with low coverage and add the missing test cases"
> Bring test coverage for everything under src/services/ to at least 80%.
> Cover not just happy paths, but also edge cases and error scenarios.

Pattern 5: Standardizing API Response Formats

> Standardize all API endpoint responses to this format:
>
> Success: { success: true, data: T }
> Failure: { success: false, error: { code: string, message: string } }
>
> Update the frontend code to match the new format.

Tips for Safe Refactoring

1. Verify Tests First

> Run npm test first and make sure all existing tests pass.
> If any tests are failing, report them before making changes.

2. Work Incrementally

Refactor module by module instead of everything at once.

> Start by refactoring only src/services/userService.ts.
> Verify that tests pass after the changes before moving on.

3. Review the Diff

> Show me the git diff. If it's too large, summarize the changes by file.

4. Use a Separate Branch

git checkout -b refactor/error-handling
claude
> Start the error handling refactoring...

Real-World Example: Modernizing Legacy Code

Here’s how to incrementally modernize an older codebase:

> Modernize this project with the following changes:
> 1. Replace var with const/let
> 2. Convert callback functions to async/await
> 3. Convert require to import
> 4. Verify tests pass after each change
> 5. Proceed one step at a time and report results at each stage

Conclusion

With Claude Code, refactoring that used to take days can be done in hours. The keys are: provide specific rules, work incrementally, and always validate with tests. Start with a small module and see the results for yourself.

Ad Space (rectangle)
#Claude Code #refactoring #code quality #automation #TypeScript