Refactor Operations

SkillFiles & storage

Safe refactoring patterns - extract, rename, restructure with test-driven methodology and dead code detection. Use for: refactor, refactoring, extract function, extract component, rename, move file, restructure, dead code, unused imports, code smell, duplicate code, long function, god object, feature envy, DRY, technical debt, cleanup, simplify, decompose, inline, pull up, push down, strangler fig, parallel change.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the Refactor Operations skill

What this skill tells your AI

The instructions your AI receives, as published by 0xdarkmatter/claude-mods in skills/refactor-ops/SKILL.md and read by ahel’s review.

Comprehensive refactoring skill covering safe transformation patterns, code smell detection, dead code elimination, and test-driven refactoring methodology.

Refactoring Decision Tree

What kind of refactoring do you need?
│
├─ Extracting code into a new unit
│  ├─ A block of statements with a clear purpose
│  │  └─ Extract Function/Method
│  │     Identify inputs (params) and outputs (return value)
│  │
│  ├─ A UI element with its own state or props
│  │  └─ Extract Component (React, Vue, Svelte)
│  │     Move JSX/template + related state into new file
│  │
│  ├─ Reusable stateful logic (not UI)
│  │  └─ Extract Hook / Composable
│  │     React: useCustomHook, Vue: useComposable
│  │
│  ├─ A file has grown beyond 300-500 lines
│  │  └─ Extract Module
│  │     Split by responsibility, create barrel exports
│  │     Watch for circular dependencies
│  │
│  ├─ A class does too many things (SRP violation)
│  │  └─ Extract Class / Service
│  │     One responsibility per class, use dependency injection
│  │
│  └─ Magic numbers, hardcoded strings, env-specific values
│     └─ Extract Configuration
│        Constants file, env vars, feature flags
│
├─ Renaming for clarity
│  ├─ Variable, function, or method
│  │  └─ Rename Symbol
│  │     Update all references (IDE rename or ast-grep)
│  │
│  ├─ File or directory
│  │  └─ Rename File + Update Imports
│  │     git mv to preserve history, update all import paths
│  │
│  └─ Module or package
│     └─ Rename Module + Update All Consumers
│        Search for all import/require references
│        Consider re-exporting from old name temporarily
│
├─ Moving code to a better location
│  ├─ Function/class to a different file
│  │  └─ Move + Re-export from Original
│  │     Leave re-export for one release cycle
│  │
│  ├─ Files to a different directory
│  │  └─ Restructure + Update All Paths
│  │     Use IDE refactoring or find-and-replace
│  │
│  └─ Reorganize entire directory structure
│     └─ Incremental Migration
│        Move one module at a time, keep tests green
│
├─ Simplifying existing code
│  ├─ Function is too simple to justify its own name
│  │  └─ Inline Function
│  │     Replace call sites with the body
│  │
│  ├─ Variable used only once, right after assignment
│  │  └─ Inline Variable
│  │     Replace variable with expression
│  │
│  ├─ Deep nesting (> 3 levels)
│  │  └─ Guard Clauses + Early Returns
│  │     Invert conditions, return early
│  │
│  └─ Complex conditionals
│     └─ Decompose Conditional
│        Extract each branch into named function
│
└─ Removing dead code
   ├─ Unused imports
   │  └─ Lint + Auto-fix (eslint, ruff, goimports)
   │
   ├─ Unreachable code branches
   │  └─ Static analysis + manual review
   │
   ├─ Orphaned files (no imports point to them)
   │  └─ Dependency graph analysis (knip, ts-prune, vulture)
   │
   └─ Unused exports
      └─ ts-prune, knip, or manual grep for import references

Safety Checklist

Run through this checklist before starting any refactoring:

Pre-Refactoring
[ ] All tests pass (full suite, not just related tests)
[ ] Working tree is clean (git status shows no uncommitted changes)
[ ] On a dedicated branch (not main/master)
[ ] CI is green on the base branch
[ ] You understand what the code does (read it, don't assume)
[ ] Characterization tests exist for untested code you will change

During Refactoring
[ ] Each commit compiles and all tests pass
[ ] Commits are small and focused (one refactoring per commit)
[ ] No behavior changes mixed with structural changes
[ ] Running tests after every change (use --watch mode)

Post-Refactoring
[ ] Full test suite passes
[ ] No new warnings from linter or type checker
[ ] Code review requested (refactoring PRs need fresh eyes)
[ ] Performance benchmarks unchanged (if applicable)
[ ] Documentation updated (if public API changed)

Extract Patterns Quick Reference

PatternWhen to UseKey Considerations
Extract FunctionBlock of code has a clear single purpose, used or could be reusedName should describe WHAT, not HOW. Pure functions preferred.
Extract ComponentUI element has own state, props, or rendering logicProps interface should be minimal. Avoid prop drilling.
Extract Hook/ComposableStateful logic shared across componentsMust start with use. Return stable references.
Extract ModuleFile exceeds 300-500 lines, has multiple responsibilitiesOne module = one responsibility. Barrel exports for public API.
Extract Class/ServiceObject handles too many concernsDependency injection over hard-coded dependencies.
Extract ConfigurationMagic numbers, environment-specific values, feature flagsType-safe config objects over loose constants.

Rename Patterns Quick Reference

What to RenameMethodPitfalls
Variable/functionIDE rename (F2) or ast-grepString references (logs, error messages) not caught by IDE
Class/typeIDE rename + update file name to matchSerialized data may reference old name (JSON, DB)
Filegit mv old new + update all importsImport paths in test files, storybook, config files often missed
Directorygit mv + bulk import updateBarrel re-exports, path aliases in tsconfig/webpack
Package/moduleRename + re-export from old nameExternal consumers need deprecation period

Move/Restructure Quick Reference

ScenarioStrategySafety Net
Single file movegit mv + update imports + re-export from old pathrg 'old/path' to find all references
Multiple related filesMove together, update barrel exportsRun type checker after each move
Directory restructureIncremental: one directory per PRKeep old paths working via re-exports
Monorepo package splitExtract to new package, update all consumersVersion the new package, pin consumers

Dead Code Detection Workflow

Step 1: Automated Detection
│
├─ TypeScript/JavaScript
│  ├─ knip (comprehensive: files, deps, exports)
│  │  └─ npx knip --reporter compact
│  ├─ ts-prune (unused exports)
│  │  └─ npx ts-prune
│  └─ eslint (unused vars/imports)
│     └─ eslint --rule 'no-unused-vars: error'
│
├─ Python
│  ├─ vulture (dead code finder)
│  │  └─ vulture src/ --min-confidence 80
│  ├─ ruff (unused imports)
│  │  └─ ruff check --select F401
│  └─ coverage.py (unreachable branches)
│     └─ coverage run && coverage report --show-missing
│
├─ Go
│  └─ staticcheck / golangci-lint
│     └─ golangci-lint run --enable unused,deadcode
│
├─ Rust
│  └─ Compiler warnings (dead_code, unused_imports)
│     └─ cargo build 2>&1 | rg 'warning.*unused'
│
Step 2: Manual Verification
│  ├─ Check if "unused" code is used via reflection/dynamic import
│  ├─ Check if exports are part of public API consumed externally
│  ├─ Check if code is used in scripts, tests, or tooling not in the scan
│  └─ Check if code is behind a feature flag or A/B test
│
Step 3: Remove with Confidence
│  ├─ Remove in small batches, not all at once
│  ├─ One commit per logical group of dead code
│  └─ Keep git history -- you can always recover

Code Smell Detection

SmellHeuristicRefactoring
Long function> 20 lines or > 5 levels of indentationExtract Function, Decompose Conditional
God objectClass with > 10 methods or > 500 linesExtract Class, Split by responsibility
Feature envyMethod uses another object's data more than its ownMove Method to the class whose data it uses
Duplicate codeSame logic in 2+ places (> 5 similar lines)Extract Function, Extract Module
Deep nesting> 3 levels of if/for/while nestingGuard Clauses, Early Returns, Extract Function
Primitive obsessionUsing strings/numbers where a type would be saferValue Objects, Branded Types, Enums
Shotgun surgeryOne change requires editing 5+ filesMove related code together, Extract Module
Dead codeUnreachable branches, unused exports/importsDelete it (git has history)
Data clumpsSame group of parameters passed together repeatedlyExtract Parameter Object or Config Object
Long parameter listFunction takes > 4 parametersExtract Parameter Object, Builder Pattern

Test-Driven Refactoring Methodology

Refactoring Untested Code
│
├─ Step 1: Write Characterization Tests
│  │  Capture CURRENT behavior, even if it seems wrong
│  │  These tests document what the code actually does
│  └─ Goal: safety net, not correctness proof
│
├─ Step 2: Verify Coverage
│  │  Run coverage tool, ensure all paths you will touch are covered
│  └─ Add more tests if coverage is insufficient
│
├─ Step 3: Refactor in Small Steps
│  │  One transformation at a time
│  │  Run tests after EVERY change
│  └─ If tests fail, undo and try smaller step
│
├─ Step 4: Improve Tests
│  │  Now that code is cleaner, write better tests
│  │  Replace characterization tests with intention-revealing tests
│  └─ Add edge cases discovered during refactoring
│
└─ Step 5: Commit and Review
   │  Separate commits: tests first, then refactoring
   └─ Reviewers can verify tests pass on old code too

Tool Reference

ToolLanguageUse CaseCommand
ast-grepMultiStructural search and replacesg -p 'console.log($$$)' -r '' -l js
jscodeshiftJS/TSLarge-scale AST-based codemodsjscodeshift -t transform.js src/
eslint --fixJS/TSAuto-fix lint violationseslint --fix 'src/**/*.ts'
ruffPythonFast linting and auto-fixruff check --fix src/
goimportsGoOrganize importsgoimports -w .
clippyRustLint and suggest improvementscargo clippy --fix
knipJS/TSFind unused files, deps, exportsnpx knip
ts-pruneTSFind unused exportsnpx ts-prune
vulturePythonFind dead codevulture src/ --min-confidence 80
ropePythonRefactoring libraryPython API for rename, extract, move
IDE renameAllRename with reference updatesF2 in VS Code, Shift+F6 in JetBrains
sdAllFind and replace in filessd 'oldName' 'newName' src/**/*.ts

Common Gotchas

GotchaWhy It HappensPrevention
Refactoring and behavior change in same commitTempting to "fix while you're in there"Separate commits: refactor first, then change behavior
Breaking public API during internal refactorRenamed/moved exports consumed by external codeRe-export from old path, deprecation warnings
Circular dependencies after extracting modulesNew module imports from original, original imports from newDependency graph check after each extraction
Tests pass but runtime breaksTests mock the refactored code, hiding the breakIntegration tests alongside unit tests
git history lost after file moveUsed cp + rm instead of git mvAlways git mv, verify with git log --follow
Renaming misses string referencesIDE rename only catches code references, not configs/docsrg 'oldName' across entire repo after rename
Over-abstracting (premature DRY)Extracting after seeing only 2 occurrencesRule of three: wait for 3 duplicates before extracting
Extracting coupled codeNew function has 8 parameters because code is entangledRefactor coupling first, then extract
Dead code removal breaks reflection/pluginsDynamic imports, dependency injection, decoratorsGrep for string references, check plugin registries
Performance regression after extractionExtra function calls, lost inlining, cache missesBenchmark before and after for hot paths
Merge conflicts from large refactoring PRLong-lived branch diverges from mainSmall PRs, merge main frequently, or use stacked PRs
Type errors after moving filesPath aliases, tsconfig paths, barrel exports not updatedRun type checker after every file move

Reference Files

FileContentsLines
references/extract-patterns.mdExtract function, component, hook, module, class, configuration -- with before/after examples in multiple languages~700
references/code-smells.mdCode smell catalog with detection heuristics, tools by language, complexity metrics~650
references/safe-methodology.mdTest-driven refactoring, strangler fig, parallel change, branch by abstraction, feature flags, rollback~550

See Also

SkillWhen to Combine
testing-opsWrite characterization tests before refactoring, test strategy for refactored code
structural-searchUse ast-grep for structural find-and-replace across codebase
debug-opsWhen refactoring exposes hidden bugs or introduces regressions
code-statsMeasure complexity before and after refactoring to quantify improvement
migrate-opsLarge-scale migrations that require systematic refactoring
git-opsBranch strategy for refactoring PRs, stacked PRs, bisect to find regressions

Signals

GitHub stars
36
Forks
5
Last commit
Aug 2026
Advanced
Catalog kind
skill
Gateway key
refactor-ops
Source
github.com/0xdarkmatter/claude-mods