Agent skill

Refactoring Patterns

by wondelai in wondelai/skills

Apply named refactoring transformations to improve code structure without changing behavior.

MITAuto-check passedDevelopment

Install Refactoring Patterns

skills CLI
$ npx skills add wondelai/skills --skill refactoring-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install wondelai/skills refactoring-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/wondelai/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/refactoring-patterns .claude/skills/refactoring-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
refactoring-patterns
GitHub stars
2.4k
Token cost
~4k tokens
SKILL.md length
1,961 words
Files
7 (incl. references)
Skills in repo
61
Repo updated
First seen
Licence
MIT

At a glance

Apply named refactoring transformations to improve code structure without changing behavior.

  • Works in 6 steps: Code Smells as Triggers → Composing Methods → Moving Features Between Objects → …
  • The user mentions refactor this
  • SKILL.md covers Core Principle, Scoring, The Refactoring Patterns… and Common Mistakes, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Refactoring Patterns is an agent skill from wondelai/skills. Apply named refactoring transformations to improve code structure without changing behavior. Use when the user mentions "refactor this", "code smells", "extract method", "replace conditional", "technical debt", "move method", "inline variable", "decompose conditional", or "clean up this messy code". Also trigger when cleaning up legacy code, preparing code for new features by restructuring, or identifying which transformation fits a specific code smell. Covers smell-driven refactoring, safe transformation…

Its SKILL.md is about 4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 7 other files, including reference files (for example `references/composing-methods.md`, `references/moving-features.md` and `references/organizing-data.md`).

It sits in Development, covering Refactoring. The repository describes itself as: Wondel.ai Agent Skills — Business, Marketing, UX & Coding Frameworks from Bestselling Books. 50 skills + 12 guided journeys for Claude Code, Codex, Cursor & other agentskills.io… The licence is MIT.

When your agent uses it

  • The user mentions refactor this
  • Replace conditional
  • Inline variable
  • Decompose conditional

Example prompts

  • “refactor this”
  • “code smells”
  • “extract method”
  • “/refactoring-patterns”

Workflow steps

6 steps, taken from the step headings in SKILL.md.

  1. Code Smells as Triggers
  2. Composing Methods
  3. Moving Features Between Objects
  4. Organizing Data
  5. Simplifying Conditional Logic
  6. Safe Refactoring Workflow

What it can do on your machine

Read from SKILL.md and the folder at commit c172996. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • amazon.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Refactoring Patterns loads about 4k tokens when it runs, and up to ~24k if it reads all its reference files. Until then it costs about 166 tokens; SKILL.md has 1,961 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~166
When it runs · the whole SKILL.md, loaded when a task matches
~4k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~24k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from wondelai/skills at commit c172996, republished under its MIT licence (© wondelai). 1,961 words, ~3,985 tokens.

Download SKILL.mdSave it as .claude/skills/refactoring-patterns/SKILL.md (or your agent's skills folder). This skill also uses 6 other files; get the full folder from GitHub.
name
refactoring-patterns
description
Apply named refactoring transformations to improve code structure without changing behavior. Use when the user mentions "refactor this", "code smells", "extract method", "replace conditional", "technical debt", "move method", "inline variable", "decompose conditional", or "clean up this messy code". Also trigger when cleaning up legacy code, preparing code for new features by restructuring, or identifying which transformation fits a specific code smell. Covers smell-driven refactoring, safe transformation sequences, and testing guards. For code-quality foundations, see clean-code. For managing complexity, see software-design-philosophy.
license
MIT
metadata.author
wondelai
metadata.version
1.4.1

Refactoring Patterns Framework

A disciplined approach to improving the internal structure of existing code without changing its observable behavior. Every refactoring follows the same loop: verify tests pass, apply one small structural change, verify tests still pass.

Core Principle

Refactoring is not rewriting. It is a sequence of small, behavior-preserving transformations, each backed by tests. You never change what the code does — only how it is organized. Big-bang rewrites fail because they combine structural change with behavioral change, making it impossible to know which broke things.

The foundation: Bad code is a natural consequence of delivering under time pressure, not a character flaw. Code smells are objective signals of degraded structure; the smell catalog tells you where to look, and the refactoring catalog tells you what to do.

Scoring

Goal: 10/10. Score structural quality by how many of the eight Quick Diagnostic rows pass — score = round(passed / 8 × 10), adjusting down when a single smell is severe. Bands:

  • 9-10: no obvious smells remain, each function does one thing, names reveal intent, duplication is eliminated, conditionals use polymorphism where apt, and tests cover the refactored paths.
  • 5-6: a few smells remain (a Long Method, some duplication) but structure is mostly sound.
  • ≤3: pervasive smells — tangled conditionals, God classes, duplication everywhere — or no tests to refactor safely.

Always state the current score, name the smells driving it down, and list the specific refactorings needed to reach 10/10.

The Refactoring Patterns Framework

Six areas of focus for systematically improving code structure:

1. Code Smells as Triggers

Core concept: Code smells are surface indicators of deeper structural problems — not bugs, but signals that the design makes code harder to understand, extend, or maintain. Each smell maps to named refactorings that fix it.

Why it works: Named smells give teams objective criteria instead of subjective "I don't like this" — "This is Feature Envy" points directly at the fix.

Key insights:

  • Smells cluster into five families: Bloaters, Object-Orientation Abusers, Change Preventers, Dispensables, Couplers
  • Long Method is the most common smell; Duplicate Code is the most expensive
  • A method that needs a comment to explain what it does is a smell — extract and name the block instead
  • Shotgun Surgery (one change, many classes) and Divergent Change (one class, many reasons to change) are opposite signals of misplaced responsibilities
  • Primitive Obsession — raw strings/ints instead of small domain objects — spreads errors and duplication

Code applications:

ContextPatternExample
Method > 10 linesExtract MethodPull loop body into calculateLineTotal()
One change touches many classes (Shotgun Surgery)Move Method/FieldGather the scattered behavior into one class
Same params in many methodsIntroduce Parameter ObjectstartDate, endDate → DateRange
Copy-pasted logicExtract Method + Pull Up MethodShare via common method or base class

See references/smell-catalog.md when you need to name a smell and its fix — all five families (Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers) with detection heuristics and the refactoring each maps to.

2. Composing Methods

Core concept: Most refactoring starts here: break long methods into smaller, well-named pieces that read like prose — high-level steps delegating to clearly named helpers.

Why it works: Short methods with intention-revealing names eliminate comments, make bugs obvious at a glance, and enable reuse; a method call costs nothing to read when the name says everything.

Key insights:

  • Extract Method is the single most important refactoring — master it first
  • Urge to write a comment? Extract the block and use the comment as the method name
  • Inline Method when the body is as clear as the name — indirection without value is noise
  • Replace Temp with Query for computed values used in multiple places; Split Temporary Variable when one temp serves two purposes
  • Replace Method with Method Object when locals are too tangled to extract — they become fields

Code applications:

ContextPatternExample
Block with a commentExtract Method// check eligibility → isEligible()
Temp used onceInline VariableDrop const price = order.getPrice()
Trivial delegating methodInline MethodInline return deliveries > 5 if used once
Method with many tangled localsReplace Method with Method ObjectLocals become fields in a new class

See references/composing-methods.md when applying any method-level transformation — step-by-step mechanics and before/after code for Extract/Inline Method, Extract/Inline Variable, Replace Temp with Query, Split Temporary Variable, and Replace Method with Method Object.

3. Moving Features Between Objects

Core concept: The key OO design decision is where responsibilities live. When Feature Envy, excessive coupling, or unbalanced class sizes show a method or field is in the wrong class, move it where it belongs.

Why it works: A method placed away from the data it uses creates invisible cross-class dependencies, so one logical change ripples across many files — Shotgun Surgery. Co-locating method and data confines the change to one class.

Key insights:

  • Move Method when a method uses more of another class's features than its own; Move Field likewise
  • Extract Class when one class does two things — split along the axis of change; Inline Class when one does too little
  • Hide Delegate enforces the Law of Demeter; Remove Middle Man undoes it when forwarding becomes the whole class
  • Resolve that tension case by case: hide the delegate when the chain is unstable, remove the middle man when it's pure forwarding

Code applications:

ContextPatternExample
Method envies another classMove MethodcalculateShipping() from Order to ShippingPolicy
God class 500+ linesExtract ClassPull Address fields/methods into own class
Client calls a.getB().getC()Hide DelegateAdd a.getCThroughB()
Class only forwards callsRemove Middle ManLet client call the delegate directly

See references/moving-features.md when deciding where a responsibility belongs — mechanics for Move Method/Field, Extract/Inline Class, Hide Delegate, and Remove Middle Man.

4. Organizing Data

Core concept: Raw data — magic numbers, exposed fields, integer type codes — creates subtle bugs and scatters domain knowledge. Replace primitives with objects that encapsulate behavior and enforce invariants.

Why it works: An int amount has no rounding rules or currency code; a Money object encapsulates all of it, so business rules live in one place and the type system catches errors at compile time.

Key insights:

  • Replace Magic Number with Symbolic Constant — the simplest data refactoring; it names intent
  • Replace Data Value with Object cures Primitive Obsession (EmailAddress, Money, Temperature)
  • Encapsulate Field and Encapsulate Collection — never expose raw fields or mutable internal lists
  • Replace Type Code with Subclasses when the code affects behavior; with Strategy when subclassing is impractical
  • Change Value to Reference when you need identity semantics (one shared Customer, not copies)

Code applications:

ContextPatternExample
if (status == 2)Replace Magic Numberif (status == ORDER_SHIPPED)
String email passed everywhereReplace Data Value with ObjectEmailAddress class with validation
Getter returns mutable listEncapsulate CollectionReturn Collections.unmodifiableList(items)
int typeCode with switchReplace Type Code with SubclassesEmployee → Engineer, Manager

See references/organizing-data.md when replacing primitives with objects — mechanics for Replace Data Value with Object, Change Value to Reference, Replace Magic Number, Encapsulate Field/Collection, and the Replace Type Code variants.

Show full SKILL.md (825 more words)Show less
5. Simplifying Conditional Logic

Core concept: Deeply nested if/else trees, long switches, and scattered null checks are the hardest code to read and the most bug-prone. Named refactorings decompose, consolidate, and replace conditionals with clearer structures.

Why it works: A six-branch conditional forces readers to simulate every path mentally; well-named extracted branches are self-documenting, and polymorphism eliminates whole categories of "forgot this case" bugs.

Key insights:

  • Decompose Conditional: extract condition, then-branch, and else-branch into named methods
  • Consolidate Conditional Expression: merge conditions with the same result into one named check
  • Replace Nested Conditional with Guard Clauses: handle edge cases early and return, keeping the main path unindented
  • Replace Conditional with Polymorphism is the gold standard for type-based conditionals
  • Introduce Special Case (Null Object) eliminates scattered if (x == null) checks; Introduce Assertion makes assumptions fail fast

Code applications:

ContextPatternExample
Long if with complex conditionDecompose ConditionalExtract isSummer(date) and summerCharge()
Deeply nested if/elseReplace with Guard ClausesEdge cases first, return early, flat main path
Switch on object typeReplace Conditional with PolymorphismEach type implements its own calculatePay()
if (customer == null) everywhereIntroduce Special CaseNullCustomer with safe default behavior

See references/simplifying-conditionals.md when untangling branches — before/after examples for Decompose/Consolidate Conditional, Guard Clauses, Replace Conditional with Polymorphism, Special Case, and Assertions.

6. Safe Refactoring Workflow

Core concept: Refactoring is only safe when wrapped in tests. The workflow is mechanical: run tests (green), apply one small transformation, run tests (green), commit. If tests go red, revert — don't debug a broken refactoring.

Why it works: Small steps make the failure obvious (it was the last thing you did) and reverting costs seconds; debugging a failed big-bang rewrite costs days.

Key insights:

  • Rule of Three: tolerate duplication once, note it twice, refactor on the third occurrence
  • Preparatory refactoring: restructure to make the feature easy before adding it; comprehension and litter-pickup refactoring keep code improving as you read and touch it
  • When NOT to refactor: rewriting is easier, no tests and adding them isn't feasible, or the code will be deleted soon
  • Refactor for clarity first, then profile and optimize the measured bottleneck — clear code is easier to tune
  • Branch by Abstraction and Parallel Change enable large refactorings in production without long-lived branches

Code applications:

ContextPatternExample
About to add a featurePreparatory RefactoringClean the insertion point first
Third copy of same logicRule of ThreeExtract shared logic now
Large API change in productionBranch by AbstractionAdd abstraction layer, migrate callers, remove old path
Renaming a widely-used methodParallel ChangeAdd new, deprecate old, migrate, remove

See references/refactoring-workflow.md before a large or risky refactoring — the full green-to-green cycle, when (not) to refactor, performance, Branch by Abstraction, and Parallel Change.

Common Mistakes

MistakeWhy It FailsFix
Refactoring without testsNo safety net to detect behavior changeWrite characterization tests first
Big-bang rewriteMixes structural and behavioral change; undebuggableSmallest possible steps, tests after each
Refactoring while adding featuresTwo hats at once — neither change verifiableRefactor first (commit), then add feature (commit)
Renaming without updating callersBroken build or dead codeUse IDE rename; search all references
Extracting too many tiny methodsIndirection without clarity when names are poorEach name must remove the need to read the body
Ignoring the smell catalogReinvents fixes instead of applying proven recipesLearn named smells; each maps to refactorings
Refactoring doomed codePolish on condemned code is wasteCheck the code's lifespan justifies the investment
Optimizing while refactoringConflates clarity with performanceClarity first, then profile, then optimize hot path

Quick Diagnostic

QuestionIf NoAction
Do tests pass before you start?No safety netWrite or fix tests first — never refactor red
Can you name the smell you're fixing?Refactoring by instinct, not catalogIdentify the smell, apply its prescribed refactoring
Is each method under ~10 lines?Long Methods likelyExtract Method into named steps
Does each class have one reason to change?Divergent Change or Large ClassExtract Class to separate responsibilities
Are there duplicated code blocks?The most expensive smellExtract shared logic into common method/base class
Do conditionals use polymorphism where apt?Switch Statements remainReplace Conditional with Polymorphism
Are you committing after each step?Risk losing work, mixing changesCommit after every green-to-green transformation
Is the code easier to read after your change?Refactoring added complexityRevert and try a different approach

Further Reading

The definitive guides to improving existing code:

About the Author

Martin Fowler is Chief Scientist at Thoughtworks, a signatory of the Agile Manifesto, and author of Refactoring: Improving the Design of Existing Code (1999; 2nd edition 2018), which introduced catalog-based, named refactorings to mainstream development. His catalog underpins the automated refactoring tools in every major IDE.

© wondelai, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 6 other files (references) in refactoring-patterns of wondelai/skills.

  • SKILL.md
  • references/composing-methods.md
  • references/moving-features.md
  • references/organizing-data.md
  • references/refactoring-workflow.md
  • references/simplifying-conditionals.md
  • references/smell-catalog.md

Open the folder on GitHubat commit c172996

Compare with similar skills

Refactoring Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Refactoring Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Refactoring Patterns this skillwondelai/skills2.4k—~4kAutomated safety check: PassMIT
Guidelinesakash-network/node1.1k22 repos~577Automated safety check: PassMIT
Component Refactoringlangflow-ai/langflow156k—~3.5kAutomated safety check: PassMIT
Migrate Core Code to Submodulestinyhumansai/openhuman42k—~2.6kAutomated safety check: PassGPL-3.0
Systematic Code Refactoringluongnv89/claude-howto42k—~3kAutomated safety check: PassMIT
Codexskills-directory/skill-codex1.5k3 repos~1.8kAutomated safety check: PassMIT

Similar skills

  • Guidelines

    akash-network/node

    Behavioral guidelines to reduce common LLM coding mistakes. An agent skill from akash-network/node.

    1.1k GitHub starsUsed in 22 repos~577 tokens
    DevelopmentAuto-check passed
  • Component Refactoring

    langflow-ai/langflow

    Refactor high-complexity React components in Langflow frontend.

    156k GitHub stars~3.5k tokensUpdated today
    DevelopmentAuto-check passed
  • Migrate Core Code to Submodules

    tinyhumansai/openhuman

    Plans and carries out moving non-host-specific code and its tests from the OpenHuman core into vendored tiny submodule libraries, then releases the submodule and re-pins the host.

    42k GitHub stars~2.6k tokensUpdated today
    DevelopmentAuto-check passed
  • Systematic Code Refactoring

    luongnv89/claude-howto

    Guides refactoring in phases based on Martin Fowler's method: research, test coverage check, planning and small tested steps, with your approval at each phase.

    42k GitHub stars~3k tokensUpdated 7 days ago
    DevelopmentAuto-check passed
  • Codex

    skills-directory/skill-codex

    A skill your agent uses when the user asks to run Codex CLI (codex exec, codex resume) or references OpenAI Codex for code analysis, refactoring, or automated editing

    1.5k GitHub starsUsed in 3 repos~1.8k tokens
    DevelopmentAuto-check passed
  • Ponytail

    DavidObando/gsharp

    Forces the laziest solution that actually works, simplest, shortest, most minimal.

    565 GitHub starsUsed in 8 repos~1.7k tokens
    DevelopmentAuto-check passed

More from wondelai/skills

All 61 skills in this repo
  • Crossing The Chasm

    wondelai/skills

    Navigate the technology adoption lifecycle from early adopters to mainstream market.

    2.4k GitHub stars~3.6k tokensUpdated 27 days ago
    Auto-check passed
  • Design Everyday Things

    wondelai/skills

    Apply foundational design principles: affordances, signifiers, constraints, feedback, and conceptual models.

    2.4k GitHub stars~4k tokensUpdated 27 days ago
    Auto-check passed
  • Design Sprint

    wondelai/skills

    Run a structured 5-day process to prototype, test, and validate product ideas with real users.

    2.4k GitHub stars~3.8k tokensUpdated 27 days ago
    Auto-check passed
  • Hooked UX

    wondelai/skills

    Design habit-forming product loops using the Hook Model (Trigger, Action, Variable Reward, Investment).

    2.4k GitHub stars~3.5k tokensUpdated 27 days ago
    Auto-check passed
  • Improve Retention

    wondelai/skills

    Diagnose and fix retention problems using behavior design (B=MAP).

    2.4k GitHub stars~3.8k tokensUpdated 27 days ago
    Auto-check passed
  • Monetizing Innovation

    wondelai/skills

    Design products and pricing around validated willingness to pay, from Ramanujam & Tacke's "Monetizing Innovation".

    2.4k GitHub stars~5.2k tokensUpdated 27 days ago
    Auto-check passed

Categories

Questions about Refactoring Patterns

What does Refactoring Patterns do?

Apply named refactoring transformations to improve code structure without changing behavior. Refactoring Patterns is an agent skill from wondelai/skills. Apply named refactoring transformations to improve code structure without changing behavior.

When should I use Refactoring Patterns?

Refactoring Patterns fits situations like: the user mentions refactor this; replace conditional; inline variable; decompose conditional.

How do I install Refactoring Patterns in Claude Code?

Run `npx skills add wondelai/skills --skill refactoring-patterns -a claude-code`. Or copy the skill folder (refactoring-patterns in wondelai/skills) into .claude/skills/refactoring-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Refactoring Patterns in Codex?

Run `npx skills add wondelai/skills --skill refactoring-patterns -a codex`. Or copy the skill folder (refactoring-patterns in wondelai/skills) into .agents/skills/refactoring-patterns in your project. Codex loads it when a task matches its description.

Can I use Refactoring Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add wondelai/skills --skill refactoring-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/refactoring-patterns, .gemini/skills/refactoring-patterns, .github/skills/refactoring-patterns and .opencode/skills/refactoring-patterns in your project.

What does Refactoring Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Refactoring Patterns is instructions for the agent only.

Does Refactoring Patterns access the network?

SKILL.md names 1 domain. As links in the text: amazon.com. This is read from the text; nothing was executed.

Is Refactoring Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Refactoring Patterns use?

Refactoring Patterns is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Refactoring Patterns use?

About 4k tokens (SKILL.md is roughly 16k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 20k tokens, read only when the agent opens those files.

What are the alternatives to Refactoring Patterns?

Skills that share tags, products or a category with Refactoring Patterns: Guidelines (akash-network/node, 1.1k stars), Component Refactoring (langflow-ai/langflow, 156k stars), Migrate Core Code to Submodules (tinyhumansai/openhuman, 42k stars) and Systematic Code Refactoring (luongnv89/claude-howto, 42k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Refactoring Patterns?

wondelai (a GitHub organization) maintains it in wondelai/skills, which has 2,356 GitHub stars. The repository holds 61 skills in this directory. The repository was last updated on September 10, 2026.

Source: wondelai/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.