# Refactor Code Intelligent code refactoring command that analyzes code structure and applies best practices for improved maintainability and performance --- ## Metadata **Title:** Refactor Code **Category:** commands **Author:** JSONbored **Added:** September 2025 **Tags:** refactoring, code-quality, cleanup, optimization, patterns **URL:** https://claudepro.directory/commands/refactor-code ## Overview Intelligent code refactoring command that analyzes code structure and applies best practices for improved maintainability and performance ## Content The /refactor command provides intelligent code refactoring capabilities with multiple strategies and safety checks. USAGE /refactor [options] 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 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" } } INSTALLATION CLAUDE CODE: 1) Create commands directory: mkdir -p .claude/commands 2) Create command file: touch .claude/commands/refactor-code.md 3) Add command content from the Command Content section above to .claude/commands/refactor-code.md 4) Command is now available as /refactor-code in Claude Code 5) Optional: Create personal version in ~/.claude/commands/refactor-code.md for global access Requirements: ? Claude Code CLI installed ? Project directory initialized (for project commands) CONFIGURATION Temperature: 0.3 Max Tokens: System Prompt: You are a code refactoring expert focused on improving code quality, maintainability, and performance while preserving functionality TROUBLESHOOTING 1) Refactoring breaks tests or changes functional behavior unexpectedly Solution: Use --test-first to run tests before and after. Enable --dry-run to preview changes. Create git commit before refactoring: git commit -am 'pre-refactor'. 2) Modernize flag introduces breaking changes or incompatible syntax Solution: Specify language version explicitly: --javascript --es2020. Check Node.js/browser target compatibility. Use --interactive to approve each modernization. 3) Refactored code fails linting or type checking after transformation Solution: Run linter before refactoring: npm run lint. Enable --backup to preserve original. Fix type errors: tsc --noEmit before applying changes. 4) Command fails with parse errors on valid source code files Solution: Verify language version matches codebase: check package.json engines. Update parser: npm update @babel/parser. Use --language flag explicitly for mixed-syntax files. 5) Large codebase refactoring times out or consumes excessive memory Solution: Process files incrementally: /refactor src/module1 first. Increase Node.js memory: NODEOPTIONS=--max-old-space-size=. Use --exclude for nodemodules. TECHNICAL DETAILS Documentation: https://docs.claude.ai/commands/refactor --- Source: Claude Pro Directory Website: https://claudepro.directory URL: https://claudepro.directory/commands/refactor-code This content is optimized for Large Language Models (LLMs). For full formatting and interactive features, visit the website.