Skip to main content
commandsSource-backedReview first Safety Privacy

/refactor - Code Refactoring Command for Claude

Intelligent code refactoring command that analyzes code structure and applies best practices for improved maintainability and performance

by JSONbored·added 2025-09-16·
HarnessClaude Code
Invocation:/refactor [options] <file_or_selection>
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/slash-commands, https://github.com/JSONbored/awesome-claude/blob/main/content/commands/refactor.mdx
Safety notes
Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project., Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.
Privacy notes
Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution., Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-16

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

100/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

2 safety and 2 privacy notes across 4 risk areas. Review closely: credentials & tokens, permissions & scopes, third-party handling.

4 areas
  • SafetyExecution & processesReview generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project.
  • SafetyPermissions & scopesLimit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.
  • PrivacyThird-party handlingPrompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution.
  • PrivacyCredentials & tokensRedact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.

Safety notes

  • Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project.
  • Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.

Privacy notes

  • Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution.
  • Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.

Schema details

Install type
cli
Reading time
4 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Runtime and command metadata
Command syntax
/refactor [options] <file_or_selection>
Full copyable content
/refactor [options] <file_or_selection>

About this resource

The /refactor command provides intelligent code refactoring capabilities with multiple strategies and safety checks.

Usage

/refactor [options] <file_or_selection>

Options

Refactoring Types

  • --extract-function - Extract repeated code into functions
  • --extract-variable - Extract complex expressions into variables
  • --extract-constant - Move magic numbers/strings to constants
  • --inline - Inline simple functions/variables
  • --rename - Rename variables/functions for clarity
  • --simplify - Simplify complex conditional logic
  • --modernize - Update to modern language features
  • --performance - Apply performance optimizations

Safety Options

  • --dry-run - Show proposed changes without applying
  • --interactive - Prompt for each change
  • --backup - Create backup before refactoring
  • --test-first - Run tests before and after changes

Language-Specific Options

  • --javascript - Apply JS/TS specific refactoring
  • --python - Apply Python-specific refactoring
  • --java - Apply Java-specific refactoring
  • --csharp - Apply C#-specific refactoring

Examples

Extract Function

// Before
function processUsers(users) {
  for (let user of users) {
    if (user.email && user.email.includes("@")) {
      user.isValid = true;
      user.domain = user.email.split("@")[1];
    } else {
      user.isValid = false;
      user.domain = null;
    }
  }
}

// After refactoring with --extract-function
function validateEmail(email) {
  return email && email.includes("@");
}

function extractDomain(email) {
  return email.split("@")[1];
}

function processUsers(users) {
  for (let user of users) {
    if (validateEmail(user.email)) {
      user.isValid = true;
      user.domain = extractDomain(user.email);
    } else {
      user.isValid = false;
      user.domain = null;
    }
  }
}

Extract Constants

# Before
def calculate_discount(price, customer_type):
    if customer_type == "premium":
        return price * 0.2
    elif customer_type == "regular":
        return price * 0.1
    else:
        return 0

# After refactoring with --extract-constant
PREMIUM_DISCOUNT_RATE = 0.2
REGULAR_DISCOUNT_RATE = 0.1
PREMIUM_CUSTOMER_TYPE = "premium"
REGULAR_CUSTOMER_TYPE = "regular"

def calculate_discount(price, customer_type):
    if customer_type == PREMIUM_CUSTOMER_TYPE:
        return price * PREMIUM_DISCOUNT_RATE
    elif customer_type == REGULAR_CUSTOMER_TYPE:
        return price * REGULAR_DISCOUNT_RATE
    else:
        return 0

Modernize Code

// Before (ES5 style)
function getUserNames(users) {
  var names = [];
  for (var i = 0; i < users.length; i++) {
    if (users[i].active) {
      names.push(users[i].name);
    }
  }
  return names;
}

// After refactoring with --modernize
function getUserNames(users) {
  return users.filter((user) => user.active).map((user) => user.name);
}

Refactoring Patterns

Design Patterns

  • Strategy Pattern - Replace conditional logic with strategy objects
  • Factory Pattern - Extract object creation logic
  • Observer Pattern - Implement event-driven architecture
  • Decorator Pattern - Add functionality without inheritance

Code Smells Detection

  • Long Method - Break down large functions
  • Large Class - Split into focused classes
  • Duplicate Code - Extract common functionality
  • Long Parameter List - Use parameter objects
  • Feature Envy - Move methods to appropriate classes

Performance Optimizations

  • Lazy Loading - Load resources only when needed
  • Memoization - Cache expensive computations
  • Batch Operations - Combine multiple operations
  • Async Optimization - Convert synchronous to asynchronous

Safety Measures

Pre-refactoring Checks

  • Syntax validation
  • Type checking (TypeScript, etc.)
  • Lint rule compliance
  • Test coverage analysis

Post-refactoring Validation

  • Automated test execution
  • Code quality metrics comparison
  • Performance benchmarking
  • Security vulnerability scanning

Integration

IDE Integration

  • VS Code extension support
  • IntelliJ plugin compatibility
  • Vim/Neovim integration
  • Emacs package support

CI/CD Integration

  • Pre-commit hooks
  • GitHub Actions workflow
  • GitLab CI pipeline
  • Jenkins job integration

Configuration

Create a .refactor.json file in your project root:

{
  "rules": {
    "maxFunctionLength": 20,
    "maxParameterCount": 4,
    "enforceConstantExtraction": true,
    "modernizeFeatures": true
  },
  "exclude": ["node_modules/**", "dist/**", "*.test.js"],
  "backup": {
    "enabled": true,
    "directory": ".refactor-backups"
  }
}

Source citations

Add this badge to your README

Show that /refactor - Code Refactoring Command for Claude is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/commands/refactor.svg)](https://heyclau.de/entry/commands/refactor)

How it compares

/refactor - Code Refactoring Command for Claude side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Intelligent code refactoring command that analyzes code structure and applies best practices for improved maintainability and performance

Open dossier

Custom slash command for behavior-preserving, scoped refactors of one file, function, or selection — stays inside a narrow ownership boundary for a reviewable, PR-sized change instead of a repo-wide pass

Open dossier

Deploy 100 specialized sub-agents for comprehensive enterprise-grade security, performance, and optimization audit of production codebase

Open dossier

Advanced performance optimization with bottleneck analysis, memory profiling, and automated improvements

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categorycommandscommandscommandscommands
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-162025-09-162025-10-252025-09-16
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesReview generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project. Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.This command edits source files in your working directory. Review the proposed diff before accepting, and keep your work committed or backed up so changes are easy to revert. It is scoped on purpose — it should not perform repository-wide rewrites. Run your tests after applying to confirm behavior is unchanged.Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project. Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.Review generated changes and commands before applying them; slash commands can ask the agent to read, write, edit, or run tools in the current project. Limit scope to the intended files and run in a trusted checkout when the command analyzes code, tests, security findings, or generated output.
Privacy notesPrompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution. Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.The command reads the local source you point it at so Claude can refactor it within your session. It does not send your code to any third-party service beyond the model you are already using.Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution. Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.Prompts, source files, logs, errors, dependency metadata, and generated reports may be sent to the configured AI model during command execution. Redact secrets, customer data, private repository details, and proprietary code before sharing command output outside the workspace.
Prerequisites— none listed— none listed— none listed— none listed
Install
/refactor [options] <file_or_selection>
/refactor-code <file, function, or selection>
/security-audit [scope]
/optimize [options] <file_or_function>
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.