Refactoring
Intro
Refactoring is changing the structure of code without changing its
observable behavior. Do it in small, test-protected steps, one
transformation at a time, and never mix it with feature changes in
the same commit.
Overview
Verify the safety net first
Before any refactoring, run the existing tests and confirm they
pass. If no tests cover the code you are about to change, write
characterization tests first — tests that capture current behavior,
not desired behavior. Plan the refactoring as a sequence of atomic
transformations where each step keeps the suite green, and commit
after each step. The golden rule: never mix refactoring with feature
changes in the same commit.
Identify code smells
Scan systematically for the well-known smells. The full catalog
lives in references/code-smells.md; the most common offenders:
| Smell |
What to look for |
| Long Method |
Function > 20 lines or doing more than one thing |
| Large Class |
Class with > 5 responsibilities or > 300 lines |
| Long Parameter List |
Function with > 3 parameters |
| Feature Envy |
Method uses another object's data more than its own |
| Data Clumps |
Same group of variables appears together repeatedly |
| Primitive Obsession |
Strings/ints where a domain type belongs |
| Shotgun Surgery |
One change requires edits in many unrelated files |
| Divergent Change |
One class changed for multiple unrelated reasons |
| Duplicate Code |
Same logic in two or more places |
| Dead Code |
Unreachable or unused code |
Apply Fowler's refactoring catalog
Match smells to specific refactorings:
- Composing methods — Extract Function, Inline Function, Extract
Variable, Replace Temp with Query.
- Moving features — Move Function/Field, Extract Class, Inline
Class.
- Simplifying conditionals — Replace Nested Conditional with
Guard Clauses, Decompose Conditional, Replace Conditional with
Polymorphism, Introduce Null Object.
- Organizing data — Introduce Parameter Object, Replace Magic
Number with Constant, Encapsulate Collection.
- Generalization — Pull Up / Push Down Method, Extract
Interface/Trait, Replace Inheritance with Composition.
Apply GoF patterns when they simplify
Only introduce a design pattern when it solves a concrete problem,
never speculatively. The full catalog is in
references/gof-patterns.md. Most commonly useful: Strategy,
Observer, Factory Method, Builder, Adapter, Decorator, Command,
State, Template Method, Iterator. Warning signs of overuse: adding
a pattern "just in case", pattern adds more code than it removes,
only one implementation exists, the team cannot explain why.
Example
User says "this function is too long". The agent identifies three
distinct responsibilities, extracts each into a named helper
keeping the original as a high-level orchestrator, runs tests after
each extraction, and commits each extraction separately.
Gotchas
Agent-specific failure modes — provider-neutral pause-and-self-check items:
- Mixing refactoring with feature changes in the same commit. When a commit changes both structure and behavior, reviewers cannot verify that behavior was preserved, and rollback becomes surgical. Keep refactoring commits separate; the commit message should start with
refactor:.
- Starting without a test safety net. If the code has no tests, changing its structure with no verification is guessing. Write characterization tests first — tests that capture current behavior, not desired behavior — then refactor.
- Big-bang rewrite instead of incremental transformation. Full rewrites take longer, introduce more bugs, and stall new features during the rewrite. Refactor incrementally: one smell, one transformation, one commit, tests green throughout.
- Removing code assumed to be dead without verifying. Dynamic dispatch, reflection, plugin systems, and config-driven loads can call code that static analysis says is unreachable. Search for all invocation paths before deleting anything.
- Speculative generality. Adding extension points, plugin hooks, or configuration flags "just in case" is not refactoring — it is adding untested code for hypothetical future requirements. Refactor to the current need, not the imagined future.
- Pattern cargo-culting. Introducing a design pattern because it sounds clever adds indirection and complexity without value. Apply a pattern only when it solves a concrete, present problem — and only after the "rule of three" (three similar occurrences) is met.
- Skipping the refactor step after green. The refactor step is where the design payoff from TDD-style cycles lives. Skipping it means the test suite is green but the technical debt is accumulating.
Full reference
Modern considerations
For async/concurrent code, extract async boundaries clearly (sync
core, async shell), replace callback chains with async/await where
possible, and isolate side effects at the edges. For
functional-style code, replace mutable loops with map/filter/reduce
pipelines, extract pure functions from impure ones, and use
algebraic types (enums/unions) over class hierarchies for closed
sets.
Smell-to-pattern map
| Smell / situation |
Candidate pattern |
| Complex conditional logic on types |
Strategy, State, polymorphism |
| Growing switch/match statements |
Factory Method + polymorphism |
| Duplicated algorithm with variations |
Template Method |
| Complex object construction |
Builder |
| Third-party integration coupling |
Adapter |
| Need to add behavior to existing code |
Decorator |
| Multiple objects reacting to events |
Observer |
| Complex state-dependent behavior |
State |
| Request needs undo/queue/log |
Command |
| Many interacting objects |
Mediator |
Selecting a pattern (rule of three)
Wait until you see a need in three places before abstracting. One
occurrence is a fact, two is a coincidence, three is a pattern.
Premature abstraction is harder to undo than late abstraction
because the wrong shape constrains future changes.
Anti-patterns
- Mixing refactoring with feature work in the same commit
- Refactoring without a test safety net
- Speculative generality — adding hooks "just in case"
- Pattern cargo-culting — applying GoF because it sounds clever
- Big-bang rewrites instead of incremental transformation
- Removing dead code without checking it is truly unreachable
(search for dynamic dispatch, reflection, config-driven loads)
Example: extracting test seams
To make code more testable, identify concrete dependencies (file
I/O, HTTP, database), extract interfaces/traits at those
boundaries (Adapter pattern), move domain logic into pure
functions, and introduce dependency injection so tests can supply
fakes. This is refactoring in service of testability, not feature
work, and should ship in its own commit series.
1---2name: refactoring3description: |4 Systematic refactoring with Fowler's catalog, GoF patterns, and code smell detection. Use when restructuring code without changing behavior — cleaning up smells, applying patterns, reducing duplication, or preparing a module for an upcoming feature.5metadata:6 source: https://skillmd.com/skills/projectious-work/refactoring7 processkit:8 apiVersion: processkit.projectious.work/v19 id: SKILL-refactoring10 version: "1.1.0"11 created: 2026-04-06T00:00:00Z12 category: engineering13 layer: 314---1516# Refactoring1718## Intro1920Refactoring is changing the structure of code without changing its21observable behavior. Do it in small, test-protected steps, one22transformation at a time, and never mix it with feature changes in23the same commit.2425## Overview2627### Verify the safety net first2829Before any refactoring, run the existing tests and confirm they30pass. If no tests cover the code you are about to change, write31characterization tests first — tests that capture current behavior,32not desired behavior. Plan the refactoring as a sequence of atomic33transformations where each step keeps the suite green, and commit34after each step. The golden rule: never mix refactoring with feature35changes in the same commit.3637### Identify code smells3839Scan systematically for the well-known smells. The full catalog40lives in `references/code-smells.md`; the most common offenders:4142| Smell | What to look for |43|---|---|44| Long Method | Function > 20 lines or doing more than one thing |45| Large Class | Class with > 5 responsibilities or > 300 lines |46| Long Parameter List | Function with > 3 parameters |47| Feature Envy | Method uses another object's data more than its own |48| Data Clumps | Same group of variables appears together repeatedly |49| Primitive Obsession | Strings/ints where a domain type belongs |50| Shotgun Surgery | One change requires edits in many unrelated files |51| Divergent Change | One class changed for multiple unrelated reasons |52| Duplicate Code | Same logic in two or more places |53| Dead Code | Unreachable or unused code |5455### Apply Fowler's refactoring catalog5657Match smells to specific refactorings:5859- **Composing methods** — Extract Function, Inline Function, Extract60 Variable, Replace Temp with Query.61- **Moving features** — Move Function/Field, Extract Class, Inline62 Class.63- **Simplifying conditionals** — Replace Nested Conditional with64 Guard Clauses, Decompose Conditional, Replace Conditional with65 Polymorphism, Introduce Null Object.66- **Organizing data** — Introduce Parameter Object, Replace Magic67 Number with Constant, Encapsulate Collection.68- **Generalization** — Pull Up / Push Down Method, Extract69 Interface/Trait, Replace Inheritance with Composition.7071### Apply GoF patterns when they simplify7273Only introduce a design pattern when it solves a concrete problem,74never speculatively. The full catalog is in75`references/gof-patterns.md`. Most commonly useful: Strategy,76Observer, Factory Method, Builder, Adapter, Decorator, Command,77State, Template Method, Iterator. Warning signs of overuse: adding78a pattern "just in case", pattern adds more code than it removes,79only one implementation exists, the team cannot explain why.8081### Example8283User says "this function is too long". The agent identifies three84distinct responsibilities, extracts each into a named helper85keeping the original as a high-level orchestrator, runs tests after86each extraction, and commits each extraction separately.8788## Gotchas8990Agent-specific failure modes — provider-neutral pause-and-self-check items:9192- **Mixing refactoring with feature changes in the same commit.** When a commit changes both structure and behavior, reviewers cannot verify that behavior was preserved, and rollback becomes surgical. Keep refactoring commits separate; the commit message should start with `refactor:`.93- **Starting without a test safety net.** If the code has no tests, changing its structure with no verification is guessing. Write characterization tests first — tests that capture current behavior, not desired behavior — then refactor.94- **Big-bang rewrite instead of incremental transformation.** Full rewrites take longer, introduce more bugs, and stall new features during the rewrite. Refactor incrementally: one smell, one transformation, one commit, tests green throughout.95- **Removing code assumed to be dead without verifying.** Dynamic dispatch, reflection, plugin systems, and config-driven loads can call code that static analysis says is unreachable. Search for all invocation paths before deleting anything.96- **Speculative generality.** Adding extension points, plugin hooks, or configuration flags "just in case" is not refactoring — it is adding untested code for hypothetical future requirements. Refactor to the current need, not the imagined future.97- **Pattern cargo-culting.** Introducing a design pattern because it sounds clever adds indirection and complexity without value. Apply a pattern only when it solves a concrete, present problem — and only after the "rule of three" (three similar occurrences) is met.98- **Skipping the refactor step after green.** The refactor step is where the design payoff from TDD-style cycles lives. Skipping it means the test suite is green but the technical debt is accumulating.99100## Full reference101102### Modern considerations103104For async/concurrent code, extract async boundaries clearly (sync105core, async shell), replace callback chains with async/await where106possible, and isolate side effects at the edges. For107functional-style code, replace mutable loops with map/filter/reduce108pipelines, extract pure functions from impure ones, and use109algebraic types (enums/unions) over class hierarchies for closed110sets.111112### Smell-to-pattern map113114| Smell / situation | Candidate pattern |115|---|---|116| Complex conditional logic on types | Strategy, State, polymorphism |117| Growing switch/match statements | Factory Method + polymorphism |118| Duplicated algorithm with variations | Template Method |119| Complex object construction | Builder |120| Third-party integration coupling | Adapter |121| Need to add behavior to existing code | Decorator |122| Multiple objects reacting to events | Observer |123| Complex state-dependent behavior | State |124| Request needs undo/queue/log | Command |125| Many interacting objects | Mediator |126127### Selecting a pattern (rule of three)128129Wait until you see a need in three places before abstracting. One130occurrence is a fact, two is a coincidence, three is a pattern.131Premature abstraction is harder to undo than late abstraction132because the wrong shape constrains future changes.133134### Anti-patterns135136- Mixing refactoring with feature work in the same commit137- Refactoring without a test safety net138- Speculative generality — adding hooks "just in case"139- Pattern cargo-culting — applying GoF because it sounds clever140- Big-bang rewrites instead of incremental transformation141- Removing dead code without checking it is truly unreachable142 (search for dynamic dispatch, reflection, config-driven loads)143144### Example: extracting test seams145146To make code more testable, identify concrete dependencies (file147I/O, HTTP, database), extract interfaces/traits at those148boundaries (Adapter pattern), move domain logic into pure149functions, and introduce dependency injection so tests can supply150fakes. This is refactoring in service of testability, not feature151work, and should ship in its own commit series.