From superpowers
Expert code refactoring that strictly preserves existing behavior. Use when asked to refactor code, improve code structure, reduce duplication, extract methods/classes/modules, simplify complex conditionals, improve naming, apply design patterns, reduce complexity, clean up code, make code more maintainable/readable/testable, decompose large functions/classes, or find cross-file patterns and commonalities to consolidate. Language-agnostic. Triggers on requests like "refactor this", "clean up this code", "this function is too long", "reduce duplication", "simplify this logic", "make this more maintainable", "make this more object-oriented", "apply design patterns", "find common patterns", or "what can be consolidated across files".
How this skill is triggered — by the user, by Claude, or both
Slash command
/superpowers:code-refactorerThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Expert, behavior-preserving code refactoring across all languages and paradigms.
Expert, behavior-preserving code refactoring across all languages and paradigms.
Before any code changes, assess whether refactoring is the right response. "Recommend not refactoring" or "document instead" are valid, expert-level outputs.
Assess these code-observable signals:
| Code Signal | Recommended Response |
|---|---|
| Behavioral coupling detected (state machines, ordered side effects, varied retry strategies) + long stability in git history | Don't refactor. Add documentation explaining the structure instead. |
| Many callers + no test coverage | Strategy only. Provide a phased plan starting with characterization tests. No code changes yet. |
| Performance-critical hot path (tight loop, benchmark tests present) | Quantify first. Estimate per-call overhead of each proposed change before recommending it. |
| Recently created code, few dependents, experimental branch | Lightweight refactoring. Quick wins only — naming, deduplication of active pain points. |
| Adequate test coverage + moderate caller count + clear structural issues | Proceed with standard refactoring workflow. |
After the gate decision, always enumerate at least 3-4 candidate approaches (including "do nothing" and "document only") with a 1-sentence rejection or acceptance rationale for each. For the recommended approach, identify threshold-based branch points:
When recommending "don't refactor," always include a contingency for the mandatory case (e.g., shadow-mode implementation with gradual rollout). When recommending limited changes, describe what would justify deeper refactoring later.
If the gate permits proceeding, adapt your analytical approach based on what you observed:
per-call overhead × call volumeUse this workflow when the Appropriateness Gate indicates standard refactoring is appropriate.
Scan for these common smells to determine what refactoring is needed:
| Smell | Symptom | Typical Refactoring | Contraindication |
|---|---|---|---|
| Long Method | Function > ~20 lines or does multiple things | Extract Method | Hot path with high call volume — function call overhead matters. Behavioral coupling — ordering may be intentional. |
| Large Class | Class has too many responsibilities | Extract Class, Move Method | Many external dependents — use strangler fig instead. |
| Duplicated Code | Same logic in 2+ places | Extract Method/Function, Pull Up | Hot path — inlining may be deliberate for performance. |
| Near-Duplicate Code | Structurally similar blocks with minor variations | Parameterize differences, extract shared template | Blocks may diverge in the future (different domains). Only 2 instances + short — wait for a third (Rule of Three). |
| Feature Envy | Method uses another class's data more than its own | Move Method | Many callers depend on current location. |
| Data Clumps | Same group of fields/params appear together | Extract Class/Record | — |
| Primitive Obsession | Overuse of primitives instead of small objects | Replace Primitive with Object | — |
| Long Parameter List | Function takes > 3-4 parameters | Introduce Parameter Object | Many callers + no tests — add new overload with deprecation instead of changing signature. |
| Divergent Change | One class modified for unrelated reasons | Extract Class | — |
| Shotgun Surgery | One change requires edits across many classes | Move Method, Inline Class | — |
| Switch Statements | Repeated switch/if-else on same type field | Replace Conditional with Polymorphism | Fewer than 3 branches or pattern doesn't repeat. |
| Speculative Generality | Unused abstractions "for the future" | Collapse Hierarchy, Inline Class | — |
| Dead Code | Unreachable or unused code | Remove Dead Code | Verify via grep/search that code is truly unreachable — feature flags or reflection may use it. |
| Comments as Deodorant | Comments explaining confusing code | Rename, Extract Method (make code self-documenting) | Comments may explain why (business rules, edge cases) — preserve those. Only remove comments that explain what when the code is made self-explanatory. |
| Cross-File Duplication | Same logic pattern repeated across multiple files with only entity/field names varying | Extract shared base class, factory function, decorator, or utility module (see Cross-File Pattern Discovery) | Instances in different bounded contexts — coupling is worse than duplication. Pattern still evolving — premature abstraction. Only 2 short instances — Rule of Three. |
| Missing OOP Structure | Procedural patterns in OO code: switch/map dispatch instead of polymorphism, data+functions not co-located, cross-cutting concerns copy-pasted, complex conditionals on state fields | Apply appropriate design pattern (see OOP Design Pattern Opportunities below) | Code is in a scripting/functional context where OOP adds ceremony without benefit. Pattern has fewer than 3 instances — wait for a third. |
Determine the refactoring approach based on the request:
"This function/method is too long" → Extract Method. Identify clusters of related statements, especially those preceded by a comment or blank line. Each cluster becomes a method named after its intent.
"There's duplicated code" → Extract shared logic into a common function/method. If duplication is across classes, consider Extract Superclass or a shared utility. Also scan for near-duplicates: code blocks with the same control flow but different names, types, or constants. Parameterize the varying parts into a shared function. See the "Unify Near-Duplicate Code" section in references/refactoring-catalog.md for detailed examples.
"This is hard to understand" → Rename variables/methods for clarity, extract well-named helper methods, replace magic numbers with named constants, simplify nested conditionals with guard clauses or early returns.
"This class does too much" → Identify distinct responsibilities. Extract Class for each cohesive group of fields and methods. Use composition to reconnect.
"I want to add tests but can't" → Identify and break hidden dependencies. Extract interfaces, inject dependencies, extract pure functions from side-effectful code.
"Simplify these conditionals" → Apply guard clauses for early returns, decompose complex boolean expressions into named methods, consider Replace Conditional with Polymorphism for type-based switching.
"Find common patterns across files" or "What can be consolidated?" → Use the Cross-File Pattern Discovery workflow. Start with structural reconnaissance (parallel names, shared imports, repeated signatures), then deep-analyze each candidate cluster, then plan consolidation with explicit migration order.
"Make this more object-oriented" or "Apply design patterns" or "This class has too many dependencies/responsibilities" → See the OOP Design Pattern Opportunities section below. Scan for procedural patterns that would benefit from polymorphism, encapsulation, or composition. Common triggers: switch/map dispatch, data+behavior separation, copy-pasted cross-cutting concerns, complex state-dependent conditionals.
"General cleanup"→ Prioritize: dead code removal → naming improvements → extract method for long functions → reduce duplication → simplify conditionals.
if (isValid(x) && isAuthorized(user)) over if (x != null && x.status == 1 && user.role == "admin")remainingRetries not r or count)calculateTotalPrice not process)is/has/can/should prefix (isValid, hasPermission)When asked to reduce duplication, find common patterns, or improve consistency across a codebase, perform a systematic cross-file search before proposing changes. This goes beyond spotting duplication in code you can already see — it actively hunts for structural commonalities scattered across the project.
Map the codebase structure to identify likely duplication zones:
UserService, OrderService, ProductService; or user_handler.py, order_handler.py). Parallel names strongly predict parallel implementations.validate*, handle*, process*, create*).try/catch/try/except blocks, retry logic, or error-wrapping patterns that appear in multiple files.// TODO: extract, # same as in X), copy-paste artifacts, or structurally identical code blocks.For each candidate pattern cluster found in Phase 1:
For each validated pattern:
| Pattern | How to Detect | Consolidation Strategy | Watch Out For |
|---|---|---|---|
| Parallel entity handlers — Same CRUD/workflow logic repeated per entity (User, Order, Product) | Search for functions named create*, update*, delete* across service/handler files | Generic handler factory, base class with entity-specific overrides, or higher-order function | Entity-specific business rules that break the abstraction — keep hooks/extension points |
| Scattered validation logic — Same validation rules reimplemented in multiple places | Search for regex patterns, range checks, or format validations on the same field type | Shared validator module with composable rules | Validation rules that look identical but have context-dependent edge cases |
| Repeated data transformation — Same mapping/conversion logic across files | Search for similar .map() chains, field-by-field copies, or serialization patterns | Shared mapper/transformer functions or a mapping registry | Transformations that will diverge as schemas evolve independently |
| Copy-pasted error handling — Identical try/catch structures with logging, retry, fallback | Search for similar catch blocks, retry loops, or error-wrapping patterns | Error-handling middleware, decorators, or wrapper functions | Error handlers that look similar but have intentionally different retry/fallback strategies |
| Repeated configuration/setup — Same initialization boilerplate across modules | Search for similar constructor patterns, config loading, or connection setup | Factory functions, builder pattern, or shared config module | Setup that looks boilerplate but encodes environment-specific tuning |
| Parallel test structures — Same test setup/teardown/assertion patterns across test files | Search for similar beforeEach/setUp blocks and assertion sequences | Shared test fixtures, custom assertion helpers, or test base classes | Test readability — over-abstracting tests makes failures harder to diagnose |
| Duplicated middleware/decorators — Same cross-cutting concern (auth, logging, caching) reimplemented per endpoint | Search for repeated auth checks, logging calls, or cache-key patterns at function boundaries | Extract middleware, decorators, or aspect-oriented wrappers | Middleware that looks identical but has endpoint-specific behavior embedded |
| Structural near-duplicates — Functions with identical control flow but different field/type references | Search for functions with same line count and same branching structure in related files | Parameterize differences via callbacks, generics, or configuration objects | Apparent similarity masking genuinely different domain logic |
Use targeted searches to find each pattern type. Here are effective search strategies:
Find parallel naming conventions:
*Service*, *Handler*, *Controller*, *Repository*Find repeated logic by signature:
validate, parse, format, convert, handle, process, create, build(req, res), (ctx, input), or (id, options)Find structural duplication by markers:
validate → save → notify) across filesFind copy-paste artifacts:
same as, copied from, see also, similar toextract, consolidate, DRY, sharedDo not consolidate when:
When reporting cross-file patterns, structure your findings as:
When asked to make code "more object-oriented" or when you detect procedural patterns in OO code, systematically scan for these design pattern opportunities. Each entry describes the code smell that indicates the pattern, how to detect it, the pattern to apply, and when not to apply it.
| Code Smell | Detection Signal | Candidate Pattern | Contraindication |
|---|---|---|---|
| Switch/map dispatch on type or name to select behavior | A switch, dictionary lookup, or if-else chain maps keys to different code paths. Adding a new variant requires editing the switch. | Strategy — Extract each branch into a class implementing a shared interface. Dispatcher becomes a thin router. | Fewer than 4 branches, or branches share significant mutable state across a single call. |
| Similar algorithms with varying steps | Multiple methods/classes follow the same high-level sequence (validate → process → format) but differ in specific steps. Copy-paste with tweaks. | Template Method — Extract the shared skeleton into an abstract base class. Varying steps become abstract/virtual methods overridden by subclasses. | Steps will diverge significantly across variants. Only 2 instances exist (Rule of Three). Composition via callbacks/lambdas would be simpler. |
| Tight notification coupling | Class A directly calls methods on classes B, C, D to notify them of changes. Adding a new listener requires editing class A. | Observer / Event — A publishes events; B, C, D subscribe independently. New listeners require zero changes to A. | Only 1-2 listeners that are unlikely to grow. Event-driven indirection makes debugging harder when the notification chain is short and stable. |
| Complex object construction scattered or duplicated | Object creation logic (with conditional configuration, defaults, validation) is repeated across multiple call sites. Callers assemble objects step-by-step. | Factory / Builder — Centralize creation logic. Factory for single-step creation with variants; Builder for multi-step assembly with optional parts. | Object construction is trivial (just new Foo(a, b)). Only one call site exists. |
| Cross-cutting concerns copy-pasted | The same pre/post logic (logging, auth checks, caching, retry, timing) is wrapped around multiple operations. Each wrapper is copy-pasted with minor variations. | Decorator / Middleware — Wrap behavior in composable layers that share an interface with the thing they wrap. Stack them via DI or explicit composition. | Each "copy" actually has meaningfully different behavior (different retry strategies, different auth rules). Fewer than 3 instances. |
| Complex conditionals on state fields | Code checks if (status == "pending") ... else if (status == "approved") ... else if (status == "shipped") with different behavior per state. State transitions are validated in multiple places. | State — Each state becomes a class implementing a shared interface. The context object delegates to its current state. Transitions are enforced by the state objects. | Fewer than 3 states. State transitions are simple and centralized. The state-dependent behavior is trivial (just setting a field). |
| Data and behavior separated | A "data" class/struct holds fields while separate "service" functions operate on it. The service repeatedly reaches into the data's internals. (Feature Envy at scale.) | Encapsulation — Move behavior onto the data class as methods. The data object becomes a rich domain object that protects its own invariants. | The "data" class is a DTO crossing a boundary (API, serialization). Behavior genuinely belongs at a different layer. |
| Parallel hierarchies with shared boilerplate | Multiple classes follow the same structure (constructor pattern, shared helper calls, common error handling) but each has unique logic. Adding a new variant means copying an existing class and tweaking it. | Abstract Base Class + Template or Strategy with shared base — Extract the shared boilerplate into a base class. Each variant overrides only what's unique. Optionally use a second-tier base for subgroups with additional shared logic. | Variants are in different bounded contexts. The "shared" part is evolving rapidly. Composition would avoid the fragile base class problem. |
When scanning for OOP opportunities:
try/catch blocks, auth checks, caching logic, or timing code duplicated around multiple operations → Decorator/Middleware.Once you've identified a candidate:
Adapt refactoring to language idioms:
@property when extracting computed attributes; leverage dataclass or NamedTuple for data clumpsimpl blocks to group related methods; leverage pattern matching over if-else chainsFor detailed before/after examples of each refactoring type, see references/refactoring-catalog.md.
Creates structured, bite-sized implementation plans from specs or requirements before writing code. Useful for breaking down multi-step tasks into testable steps with file structure and task boundaries.
npx claudepluginhub mthalman/cc-plugins --plugin superpowers