Refactoring
Changing structure without changing behaviour: extract, rename, simplify, remove dead code.
Download all 93
Start here 1
The general, start-from-zero entry for a need in this category: it works from a blank start, asks for what it needs and hands off to the specific entries. Example: Plan a trip.
- Refactor messy code
Cleans up hard-to-work-with code in small behaviour-preserving steps, pinning behaviour with tests first and fixing what blocks your goal most. Use when code is messy and you want it easier to change.
Specific 77
One situation, audience, tool or format inside the category. Example: Plan a road trip with children.
- Simplify a complex function
Rewrites a hard-to-follow function into a clearer one with identical behaviour, using guard clauses, named steps and simpler conditions, verified by tests. Use on long or deeply nested code.
- Extract a module
Moves one responsibility out of a large file or class into its own module in small, test-verified steps, without changing behaviour or the public API. Use when a file does too many things.
- Reduce code duplication
Finds duplicated logic, separates true duplication from code that only looks alike, and merges only true duplicates behind one well-named function. Use when one fix keeps landing in many places.
- Improve naming in code
Proposes clearer names for variables, functions, types and modules, explains each rename and applies them without changing behaviour. Use when code reads poorly because of its names.
- Remove dead code safely
Finds unused code, flags, endpoints, jobs and dependencies, proves each dead with static and runtime evidence, and removes it or stages a reversible retirement. Use to shrink a codebase.
- Plan splitting a large module
Maps the responsibilities and internal dependencies of an oversized file or class and plans its split into cohesive modules, in small steps that keep tests green. Use before breaking up a god class.
- Tidy a research script
Restructures a long analysis script written by a researcher into functions, configuration and a clear entry point without changing results, and checks outputs match before and after.
- Legacy code steward
Acts as an engineer who looks after old, business-critical code, understanding before changing, pinning behaviour with characterisation tests and shipping tiny safe changes. Use on inherited systems.
- Refactoring specialist
Acts as a refactoring specialist who improves existing code in small behaviour-preserving steps, pins behaviour with tests first and stops when the code is clear enough for the next change.
- Remove needless abstraction
Finds and inlines abstractions that cost more than they give, such as single-implementation interfaces, pass-through layers, unused extension points and wrapper classes, keeping behaviour identical.
- Triage TODO and FIXME comments
Inventories TODO, FIXME and HACK comments, fixes the trivial ones, deletes stale ones, and turns the rest into ticket drafts with enough context to act on.
- Centralize scattered input validation
Replaces ad hoc input checks scattered through server code with declared schemas at the API boundary (Zod, Pydantic, Bean Validation and similar), keeping error responses the same.
- Clean up AI-generated code
Cleans up agent-written code, removing duplicated helpers, dead branches, over-defensive checks, needless comments and patterns that ignore the codebase's conventions, keeping tests green.
- Consolidate duplicate UI components
Merges near-identical buttons, modals, cards or inputs scattered across a frontend into one component with variants, then migrates call sites in groups with visual parity checks.
- Convert callbacks to async/await
Converts callback-style and promise-chain code to async/await across a module or repo without changing behaviour, keeping error handling, ordering and concurrency, with tests run before and after.
- Legacy codebase takeover track
Takes over an unfamiliar legacy codebase in gated steps, from building and running it to mapping risks, pinning behaviour with tests, a first small change and takeover notes.
- Simplify a function signature
Cleans up a function with too many parameters, boolean flag arguments, positional arguments of the same type or output parameters, and updates every caller with behaviour unchanged.
- Unify inconsistent error handling
Replaces a mix of error codes, exceptions, null returns and ad hoc messages in a module with one consistent error type and propagation style, keeping caller-visible behaviour the same.
- Remove barrel files
Replaces index.ts re-export barrel files with direct imports, using a codemod and import checks, to cut circular imports, slow test startup and bundle bloat without changing behaviour.
- Untangle stylesheet specificity
Refactors a stylesheet caught in specificity wars - !important chains, ID and deep selectors, overrides of overrides - into flat, scoped rules without changing how pages look.
- Break up a junk-drawer utils module
Breaks a grab-bag utils or helpers module into domain-owned modules, deletes unused helpers, merges duplicates and fixes every import without behaviour change.
- Move repeated handler code into middleware
Moves auth checks, logging, request validation and error wrapping repeated in every handler into middleware, decorators or filters, keeping every response identical.
- Make a cryptic regex readable
Rewrites a cryptic regular expression with named groups, verbose mode or composed parts, with tests proving it matches and captures exactly what the old one did.
- Move business logic out of controllers
Moves business rules buried in HTTP handlers, controllers, views or job handlers into plain functions or services the transport calls, so they can be reused and tested without a request.
- Remove stale feature flags safely
Finds feature flags that are fully rolled out or dead, removes each flag and its losing branch with tests passing, and leaves a cleanup list for the flag service. Use to pay down flag debt.
- Reorganize a project's folder structure
Moves a codebase from a messy or layer-based folder layout to a clear one, often grouped by feature, in scripted batches that update imports, keep git history and leave every commit building.
- Replace print statements with logging
Replaces print and console.log debugging in a script or service with a configured logger, sensible levels and context, while keeping the program's intended user-facing output intact.
- Simplify a UI component's props
Replaces a UI component's pile of boolean and one-off props with variants, composition or compound components, keeping every existing call site rendering the same during migration.
- Consolidate duplicate TypeScript types
Merges near-duplicate TypeScript interfaces and types into one source of truth with derived types (Pick, Omit, Partial, mapped types), and updates usages without changing runtime behaviour.
- Deduplicate copy-pasted CI pipelines
Merges copy-pasted CI jobs into reusable workflows, composite actions or templates, and proves each pipeline still runs the same steps with the same triggers and secrets.
- Deduplicate per-environment Kubernetes YAML
Turns copy-pasted per-environment Kubernetes manifests into a Kustomize base with overlays or Helm values, diffing the rendered output to prove each environment is unchanged.
- Improve Go error handling
Refactors Go error handling to wrapped errors with context, sentinel and typed errors checked with errors.Is and errors.As, one place that logs, and no ignored errors, without changing behaviour.
- Make Java-style Kotlin idiomatic
Cleans up Java-style or auto-converted Kotlin by removing !! and lateinit abuse, adding data classes, real nullability, expression bodies and sensible scope functions, without behaviour change.
- Modernise dated C# code
Rewrites dated C# to records, pattern matching, nullable reference types, file-scoped namespaces, using declarations and collection expressions, without behaviour change.
- Modernise dated Java code
Rewrites old Java to records, switch expressions, pattern matching for instanceof, text blocks, var and streams where they read better, for the project's Java version and without behaviour change.
- Modernise old JavaScript syntax
Rewrites dated JavaScript to modern syntax (const and let, arrow functions, destructuring, optional chaining, classes) without changing behaviour, minding this, hoisting and falsy values.
- Modernise dated Python idioms
Rewrites dated Python to current idioms (f-strings, pathlib, dataclasses, comprehensions, context managers, enumerate, type hints) for the project's Python version, without changing behaviour.
- Remove unnecessary useEffect calls
Replaces useEffect calls that copy derived state, reset state on prop changes or react to user events with computed values, keys and event handlers, keeping rendered behaviour identical.
- Restructure a firmware superloop
Restructures a tangled single-loop firmware sketch full of globals and delays into non-blocking state machines and modules, keeping behaviour and timing the same, one step at a time.
- Decouple code for testability
Breaks hard-wired dependencies such as clocks, network calls, globals and singletons behind seams so a class or module can be unit tested, keeping behaviour and public callers unchanged.
- Extract configuration from code
Finds hard-coded URLs, limits, credentials and feature switches, moves them into typed configuration with defaults and validation, and updates usages and docs without committing secrets.
- Extract reusable ORM query scopes
Pulls repeated ORM filter chains into named scopes, custom managers or query methods (Django, Rails, Laravel, SQLAlchemy and similar), proving the generated SQL is identical before and after.
- Extract repeated Tailwind class strings
Turns long Tailwind class strings repeated across templates into components or variant helpers, keeping the rendered classes and visuals identical and avoiding @apply sprawl.
- Restructure a messy dbt project
Reorganises a dbt project into staging, intermediate and mart layers, removes duplicated logic, and proves the refactored models return identical rows.
- Refactor a deep Flutter widget tree
Breaks deeply nested Flutter build methods into widget classes, adds const constructors and moves logic out of build, with no visible UI change.
- Refactor Go interfaces to idiomatic shape
Reshapes Go code so interfaces are small and defined by consumers, constructors return concrete types, and interfaces with one implementation and no test need are removed, without behaviour change.
- Refactor a massive UIKit view controller
Splits an oversized UIKit view controller into child view controllers, data sources, view models and navigation helpers, keeping lifecycle timing, delegate wiring and behaviour unchanged.
- Restructure a long shell script
Restructures a long Bash script into functions with strict mode, argument parsing, quoting fixes and usage text, or says plainly when it should be rewritten in Python.
- Restructure a hard-to-read SQL query
Rewrites a long, nested or copy-pasted SQL query into named CTEs with clear joins and filters, and proves the result set is unchanged with a row-for-row comparison query.
- Slim down fat Angular components
Moves HTTP calls, business rules and subscription handling out of oversized Angular components into services and container and presentational pairs, without changing behaviour.
Showing 50 of 77. See them all in search
Advanced 15
Expert or deep work that assumes the user can judge expert output. Example: Plan croissant lamination.
- Untangle circular dependencies
Finds circular dependencies between modules and plans breaking each cycle with interfaces, inversion or extraction in safe steps. Use when import cycles cause build errors or tangled code.
- Remove shared mutable state
Finds objects mutated from many places, such as arguments changed in place, module-level dicts and singletons with setters, and refactors them toward immutable values and single owners.
- Squash old database migrations
Squashes a long history of ORM migrations into one clean baseline that fresh databases build from and existing databases skip, proving the resulting schema is identical.
- Fix layering and dependency direction violations
Finds imports that point the wrong way between layers or modules, like domain code importing the web framework or database, fixes each with inversion or a move, and adds a check that keeps them out.
- Plan a large refactor in safe steps
Turns a large refactor into small, independently shippable steps that keep the build green, each with a rollback, using patterns like expand-contract. Use for refactors too big for one PR.
- Simplify over-clever TypeScript types
Rewrites unreadable conditional, mapped, recursive and generic TypeScript types into simpler ones that accept and reject the same code, proven by type-level tests and faster type checks.
- Replace inheritance with composition
Flattens a fragile class hierarchy, with deep chains, overridden template methods or subclasses that disable parent behaviour, into composed collaborators, step by step with behaviour kept.
- Convert blocking I/O code to async
Converts blocking Python or Node.js I/O code to async, picking async-native libraries, bridging sync callers, bounding concurrency and keeping blocking calls off the event loop, with tests.
- Refactor Terraform without recreating resources
Restructures Terraform code into modules, renames resources or switches count to for_each using moved and import blocks or state moves, so the plan shows no destroy or replace.
- Remove tangled Rails model callbacks
Replaces ActiveRecord callbacks that send emails, call APIs or update other models with explicit service calls, keeping the same side effects in the same order and transaction.
- Extract copied code into a shared package
Turns code copied between services, apps or repositories into one versioned internal package, reconciling drifted copies, defining a small public API and moving each consumer over one at a time.
- Extract service objects from fat models
Moves business workflows out of fat Rails, Django or Laravel models into service objects or domain modules, keeping data rules on the model and behaviour unchanged, one small step at a time.
- Untangle ownership workarounds in Rust
Removes needless clone calls, shared RefCell and Mutex wrappers and lifetime workarounds from compiling Rust code by restructuring ownership and borrowing, with behaviour unchanged.
- Modularize a C codebase with global state
Splits a large C codebase full of globals into modules with clear headers, static internals and opaque types, without changing behaviour or the build output's interface.
- Replace raw owning pointers with smart pointers
Converts owning raw pointers and manual new and delete in C++ code to unique_ptr, shared_ptr and RAII, making ownership explicit without changing behaviour.
Not: version or framework upgrades (migration); speed-ups (performance).