Skip to main content
command

refactor-code — Claude Code command: step-by-step refactoring

A slash command that walks Claude through 17 refactoring steps, from analysis and tests to performance checks and review prep.

Install into Claude Code · claude-code-templates All methods and platforms ↓
npx claude-code-templates@latest --command utilities/refactor-code
Open on GitHub

What refactor-code does

refactor-code turns a vague "clean this up" request into an ordered plan. The agent first identifies what needs refactoring and why, reviews existing tests and docs, and maps every dependency and call site. If coverage is missing, it writes tests before touching the code — that ordering is baked into the steps.

Changes then land in small pieces: a branch named git checkout -b refactor/$ARGUMENTS, a test run after each edit, frequent commits. The command picks from named techniques — extract method or class, rename, replace conditional with polymorphism, eliminate dead code. Separate steps cover performance, error handling, static analysis and documentation.

The argument feeds both the task description and the branch name, so keep it a short slug. Spaces or non-ASCII characters there mean extra git cleanup later. At the end the agent writes a change summary and a deployment plan with rollback.

What it helps with

  • untangle a messy module and rewrite it without changing behavior
  • add missing tests before refactoring starts
  • strip duplication and dead code from a legacy file
  • cut down long functions and nested conditionals
  • write a clear change summary for reviewers

Example prompts for the agent

  • /refactor-code payment-service
  • /refactor-code move validation logic out of UserController into its own class
  • /refactor-code simplify the nested conditionals in order-processor

How to install refactor-code

1claude-code-templates

npx claude-code-templates@latest --command utilities/refactor-code

2Manually: put the files in place

.claude/commands/refactor-code.md

Call it with /refactor-code. For all projects use ~/.claude/commands/

Questions about refactor-code

How do I install refactor-code in Claude?

Run npx claude-code-templates@latest --command utilities/refactor-code, then confirm the file landed at .claude/commands/refactor-code.md.

What does refactor-code do?

It runs refactoring in a fixed order: analysis, tests, strategy, small edits with test runs, static analysis, performance verification and review preparation.

What should I pass as the command argument?

The argument describes the refactoring goal and is inserted into both the task and the branch name refactor/$ARGUMENTS. A short slug without spaces avoids git trouble.

Source text

refactor-code.md · MIT
---
description: "Intelligently refactor and improve code quality"
---

# Intelligently Refactor and Improve Code Quality

Intelligently refactor and improve code quality

## Instructions

Follow this systematic approach to refactor code: **$ARGUMENTS**

1. **Pre-Refactoring Analysis**
   - Identify the code that needs refactoring and the reasons why
   - Understand the current functionality and behavior completely
   - Review existing tests and documentation
   - Identify all dependencies and usage points

2. **Test Coverage Verification**
   - Ensure comprehensive test coverage exists for the code being refactored
   - If tests are missing, write them BEFORE starting refactoring
   - Run all tests to establish a baseline
   - Document current behavior with additional tests if needed

3. **Refactoring Strategy**
   - Define clear goals for the refactoring (performance, readability, maintainability)
   - Choose appropriate refactoring techniques:
     - Extract Method/Function
     - Extract Class/Component
     - Rename Variable/Method
     - Move Method/Field
     - Replace Conditional with Polymorphism
     - Eliminate Dead Code
   - Plan the refactoring in small, incremental steps

4. **Environment Setup**
   - Create a new branch: `git checkout -b refactor/$ARGUMENTS`
   - Ensure all tests pass before starting
   - Set up any additional tooling needed (profilers, analyzers)

5. **Incremental Refactoring**
   - Make small, focused changes one at a time
   - Run tests after each change to ensure nothing breaks
   - Commit working changes frequently with descriptive messages
   - Use IDE refactoring tools when available for safety

6. **Code Quality Improvements**
   - Improve naming conventions for clarity
   - Eliminate code duplication (DRY principle)
   - Simplify complex conditional logic
   - Reduce method/function length and complexity
   - Improve separation of concerns

7. **Performance Optimizations**
   - Identify and eliminate performance bottlenecks
   - Optimize algorithms and data structures
   - Reduce unnecessary computations
   - Improve memory usage patterns

8. **Design Pattern Application**
   - Apply appropriate design patterns where beneficial
   - Improve abstraction and encapsulation
   - Enhance modularity and reusability
   - Reduce coupling between components

9. **Error Handling Improvement**
   - Standardize error handling approaches
   - Improve error messages and logging
   - Add proper exception handling
   - Enhance resilience and fault tolerance

10. **Documentation Updates**
    - Update code comments to reflect changes
    - Revise API documentation if interfaces changed
    - Update inline documentation and examples
    - Ensure comments are accurate and helpful

11. **Testing Enhancements**
    - Add tests for any new code paths created
    - Improve existing test quality and coverage
    - Remove or update obsolete tests
    - Ensure tests are still meaningful and effective

12. **Static Analysis**
    - Run linting tools to catch style and potential issues
    - Use static analysis tools to identify problems
    - Check for security vulnerabilities
    - Verify code complexity metrics

13. **Performance Verification**
    - Run performance benchmarks if applicable
    - Compare before/after metrics
    - Ensure refactoring didn't degrade performance
    - Document any performance improvements

14. **Integration Testing**
    - Run full test suite to ensure no regressions
    - Test integration with dependent systems
    - Verify all functionality works as expected
    - Test edge cases and error scenarios

15. **Code Review Preparation**
    - Review all changes for quality and consistency
    - Ensure refactoring goals were achieved
    - Prepare clear explanation of changes made
    - Document benefits and rationale

16. **Documentation of Changes**
    - Create a summary of refactoring changes
    - Document any breaking changes or new patterns
    - Update project documentation if needed
    - Explain benefits and reasoning for future reference

17. **Deployment Considerations**
    - Plan deployment strategy for refactored code
    - Consider feature flags for gradual rollout
    - Prepare rollback procedures
    - Set up monitoring for the refactored components

Remember: Refactoring should preserve external behavior while improving internal structure. Always prioritize safety over speed, and maintain comprehensive test coverage throughout the process.

© davila7 · MIT · davila7/claude-code-templates

Similar slash commands

All slash commands for Code review and refactoring →
safe-refactor JuliusBrussee Restructures code while preserving existing behavior, enforcing verification boundaries before structural edits. CX Codex +1 106,500installs refactor-plan official github This skill investigates a codebase and writes a step-by-step multi-file refactor plan before edits begin. Use it when the proposed change needs review first. 12,965installs review-and-refactor official github Reviews project code against local instructions and refactors parts that need changes. Use it before review or when cleaning up an existing codebase. 11,056installs refactor-method-complexity-reduce official github Refactors a chosen method by moving complex logic into helpers. Use it when nested conditions or branching make a method hard to follow. 9,992installs feature-dev official Anthropic Guides new feature work by exploring the codebase, asking for missing details, shaping the architecture, and waiting for approval before implementation. 179installs modernize official Anthropic This command guides a legacy-code modernization: it finds the system, records the goal and constraints, then gives the next command. Use it before the build work starts. ★ 44,635repo stars modernize-map official Anthropic Builds an interactive dependency and topology map of a legacy codebase, showing entry points and data flows. Helps map connections between modules before refactoring. ★ 44,635repo stars modernize-harden official Anthropic Scans a legacy system for vulnerabilities and drafts patches for Critical and High findings. It leaves the source code untouched. ★ 44,635repo stars

From the same set205

The whole set →

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor