Agent skill

Systematic Code Refactoring

by luongnv89 in 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.

MITAuto-check passedDevelopment

Install Systematic Code Refactoring

skills CLI
$ npx skills add luongnv89/claude-howto --skill refactor -a claude-code

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

GitHub CLI
$ gh skill install luongnv89/claude-howto refactor --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/luongnv89/claude-howto.git skills-src && mkdir -p .claude/skills && cp -r skills-src/03-skills/refactor .claude/skills/refactor && 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
refactor
GitHub stars
42k
Token cost
~3k tokens
SKILL.md length
1,267 words
Files
6 (incl. scripts, references)
Skills in repo
25
Repo updated
First seen
Licence
MIT

At a glance

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.

  • Works in 6 steps: Research & Analysis → Test Coverage Assessment → Code Smell Identification → …
  • Cleaning up a tangled module without changing its behavior
  • SKILL.md covers Core Principles, Workflow Overview, Phase 1: Research & Analysis and Phase 2: Test Coverage…, plus 4 more sections
  • Runs Python scripts from its folder; calls npm, pytest and python

What it does

The skill is built on five principles: external behavior stays the same, changes are small, tests are the safety net, refactoring is ongoing, and you approve each phase. Phase 1 is research and analysis. The agent first asks about scope, goals, constraints, timeline pressure and test status, then reads the target code, maps dependencies, notes existing debt markers such as TODOs and FIXMEs, presents its findings and asks for approval to continue.

Phase 2 assesses test coverage by looking for test files, running the existing tests and checking coverage where available. If tests exist and pass, the work moves on; if they are missing or incomplete, the decision comes back to you. Bundled resources include references on code smells and a refactoring catalog, two scripts, `scripts/analyze-complexity.py` and `scripts/detect-smells.py`, and a refactoring plan template.

When your agent uses it

  • Cleaning up a tangled module without changing its behavior
  • Reducing technical debt in legacy code
  • Finding and removing code smells

Example prompts

  • “Refactor the order-processing module, but ask me about scope and tests first.”
  • “Find code smells in src/billing and propose a refactoring plan.”
  • “Clean up this legacy utils file in small steps, running the tests after each one.”

Requirements

  • A way to run the project's tests
  • Python, for the bundled `.py` analysis scripts

Workflow steps

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

  1. Research & Analysis
  2. Test Coverage Assessment
  3. Code Smell Identification
  4. Refactoring Plan Creation
  5. Incremental Implementation
  6. Review & Iteration

What it can do on your machine

Read from SKILL.md and the folder at commit 556af8d. 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

    Ships 2 files in scripts/ (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • npm
    • pytest
    • python
    • mvn

    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):

    • code.claude.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

Systematic Code Refactoring loads about 3k tokens when it runs, and up to ~13k if it reads all its reference files. Until then it costs about 86 tokens; SKILL.md has 1,267 words of instructions outside code blocks.

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

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); the scripts in this folder are not scanned.

SKILL.md

The full file from luongnv89/claude-howto at commit 556af8d, republished under its MIT licence (© luongnv89). 1,267 words, ~2,981 tokens.

Download SKILL.mdSave it as .claude/skills/refactor/SKILL.md (or your agent's skills folder). This skill also uses 5 other files; get the full folder from GitHub.
name
refactor
description
Systematic code refactoring based on Martin Fowler's methodology. Use when users ask to refactor code, improve code structure, reduce technical debt, clean up legacy code, eliminate code smells, or improve code maintainability. This skill guides through a phased approach with research, planning, and safe incremental implementation.

Code Refactoring Skill

A systematic approach to refactoring code based on Martin Fowler's Refactoring: Improving the Design of Existing Code (2nd Edition). This skill emphasizes safe, incremental changes backed by tests.

"Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure." — Martin Fowler

Core Principles

  1. Behavior Preservation: External behavior must remain unchanged
  2. Small Steps: Make tiny, testable changes
  3. Test-Driven: Tests are the safety net
  4. Continuous: Refactoring is ongoing, not a one-time event
  5. Collaborative: User approval required at each phase

Workflow Overview

Phase 1: Research & Analysis
    ↓
Phase 2: Test Coverage Assessment
    ↓
Phase 3: Code Smell Identification
    ↓
Phase 4: Refactoring Plan Creation
    ↓
Phase 5: Incremental Implementation
    ↓
Phase 6: Review & Iteration

Phase 1: Research & Analysis

Objectives
  • Understand the codebase structure and purpose
  • Identify the scope of refactoring
  • Gather context about business requirements
Questions to Ask User

Before starting, clarify:

  1. Scope: Which files/modules/functions need refactoring?
  2. Goals: What problems are you trying to solve? (readability, performance, maintainability)
  3. Constraints: Are there any areas that should NOT be changed?
  4. Timeline pressure: Is this blocking other work?
  5. Test status: Do tests exist? Are they passing?
Actions
  • Read and understand the target code
  • Identify dependencies and integrations
  • Document current architecture
  • Note any existing technical debt markers (TODOs, FIXMEs)
Output

Present findings to user:

  • Code structure summary
  • Identified problem areas
  • Initial recommendations
  • Request approval to proceed

Phase 2: Test Coverage Assessment

Why Tests Matter

"Refactoring without tests is like driving without a seatbelt." — Martin Fowler

Tests are the key enabler of safe refactoring. Without them, you risk introducing bugs.

Assessment Steps
  1. Check for existing tests

    bash
    # Look for test files
    find . -name "*test*" -o -name "*spec*" | head -20
  2. Run existing tests

    bash
    # JavaScript/TypeScript
    npm test
    
    # Python
    pytest -v
    
    # Java
    mvn test
  3. Check coverage (if available)

    bash
    # JavaScript
    npm run test:coverage
    
    # Python
    pytest --cov=.
Decision Point: Ask User

If tests exist and pass:

  • Proceed to Phase 3

If tests are missing or incomplete: Present options:

  1. Write tests first (recommended)
  2. Add tests incrementally during refactoring
  3. Proceed without tests (risky - requires user acknowledgment)

If tests are failing:

  • STOP. Fix failing tests before refactoring
  • Ask user: Should we fix tests first?
Test Writing Guidelines (if needed)

For each function being refactored, ensure tests cover:

  • Happy path (normal operation)
  • Edge cases (empty inputs, null, boundaries)
  • Error scenarios (invalid inputs, exceptions)

Use the "red-green-refactor" cycle:

  1. Write failing test (red)
  2. Make it pass (green)
  3. Refactor

Phase 3: Code Smell Identification

What Are Code Smells?

Symptoms of deeper problems in code. They're not bugs, but indicators that the code could be improved.

Common Code Smells to Check

See references/code-smells.md for the complete catalog.

Quick Reference
SmellSignsImpact
Long MethodMethods > 30-50 linesHard to understand, test, maintain
Duplicated CodeSame logic in multiple placesBug fixes needed in multiple places
Large ClassClass with too many responsibilitiesViolates Single Responsibility
Feature EnvyMethod uses another class's data morePoor encapsulation
Primitive ObsessionOveruse of primitives instead of objectsMissing domain concepts
Long Parameter ListMethods with 4+ parametersHard to call correctly
Data ClumpsSame data items appearing togetherMissing abstraction
Switch StatementsComplex switch/if-else chainsHard to extend
Speculative GeneralityCode "just in case"Unnecessary complexity
Dead CodeUnused codeConfusion, maintenance burden
Analysis Steps
  1. Automated Analysis (if scripts available)

    bash
    python scripts/detect-smells.py <file>
  2. Manual Review

    • Walk through code systematically
    • Note each smell with location and severity
    • Categorize by impact (Critical/High/Medium/Low)
  3. Prioritization Focus on smells that:

    • Block current development
    • Cause bugs or confusion
    • Affect most-changed code paths
Output: Smell Report

Present to user:

  • List of identified smells with locations
  • Severity assessment for each
  • Recommended priority order
  • Request approval on priorities

Phase 4: Refactoring Plan Creation

Selecting Refactorings

For each smell, select an appropriate refactoring from the catalog.

See references/refactoring-catalog.md for the complete list.

Smell-to-Refactoring Mapping
Code SmellRecommended Refactoring(s)
Long MethodExtract Method, Replace Temp with Query
Duplicated CodeExtract Method, Pull Up Method, Form Template Method
Large ClassExtract Class, Extract Subclass
Feature EnvyMove Method, Move Field
Primitive ObsessionReplace Primitive with Object, Replace Type Code with Class
Long Parameter ListIntroduce Parameter Object, Preserve Whole Object
Data ClumpsExtract Class, Introduce Parameter Object
Switch StatementsReplace Conditional with Polymorphism
Speculative GeneralityCollapse Hierarchy, Inline Class, Remove Dead Code
Dead CodeRemove Dead Code
Plan Structure

Use the template at templates/refactoring-plan.md.

For each refactoring:

  1. Target: What code will change
  2. Smell: What problem it addresses
  3. Refactoring: Which technique to apply
  4. Steps: Detailed micro-steps
  5. Risks: What could go wrong
  6. Rollback: How to undo if needed
Show full SKILL.md (543 more words)Show less
Phased Approach

CRITICAL: Introduce refactoring gradually in phases.

Phase A: Quick Wins (Low risk, high value)

  • Rename variables for clarity
  • Extract obvious duplicate code
  • Remove dead code

Phase B: Structural Improvements (Medium risk)

  • Extract methods from long functions
  • Introduce parameter objects
  • Move methods to appropriate classes

Phase C: Architectural Changes (Higher risk)

  • Replace conditionals with polymorphism
  • Extract classes
  • Introduce design patterns
Decision Point: Present Plan to User

Before implementation:

  • Show complete refactoring plan
  • Explain each phase and its risks
  • Get explicit approval for each phase
  • Ask: "Should I proceed with Phase A?"

Phase 5: Incremental Implementation

The Golden Rule

"Change → Test → Green? → Commit → Next step"

Implementation Rhythm

For each refactoring step:

  1. Pre-check

    • Tests are passing (green)
    • Code compiles
  2. Make ONE small change

    • Follow the mechanics from the catalog
    • Keep changes minimal
  3. Verify

    • Run tests immediately
    • Check for compilation errors
  4. If tests pass (green)

    • Commit with descriptive message
    • Move to next step
  5. If tests fail (red)

    • STOP immediately
    • Undo the change
    • Analyze what went wrong
    • Ask user if unclear
Commit Strategy

Each commit should be:

  • Atomic: One logical change
  • Reversible: Easy to revert
  • Descriptive: Clear commit message

Example commit messages:

refactor: Extract calculateTotal() from processOrder()
refactor: Rename 'x' to 'customerCount' for clarity
refactor: Remove unused validateOldFormat() method
Progress Reporting

After each sub-phase, report to user:

  • Changes made
  • Tests still passing?
  • Any issues encountered
  • Ask: "Continue with next batch?"

Phase 6: Review & Iteration

Post-Refactoring Checklist
  • All tests passing
  • No new warnings/errors
  • Code compiles successfully
  • Behavior unchanged (manual verification)
  • Documentation updated if needed
  • Commit history is clean
Metrics Comparison

Run complexity analysis before and after:

bash
python scripts/analyze-complexity.py <file>

Present improvements:

  • Lines of code change
  • Cyclomatic complexity change
  • Maintainability index change
User Review

Present final results:

  • Summary of all changes
  • Before/after code comparison
  • Metrics improvements
  • Remaining technical debt
  • Ask: "Are you satisfied with these changes?"
Next Steps

Discuss with user:

  • Additional smells to address?
  • Schedule follow-up refactoring?
  • Apply similar changes elsewhere?

Important Guidelines

When to STOP and Ask

Always pause and consult user when:

  • Unsure about business logic
  • Change might affect external APIs
  • Test coverage is inadequate
  • Significant architectural decision needed
  • Risk level increases
  • You encounter unexpected complexity
Safety Rules
  1. Never refactor without tests (unless user explicitly acknowledges risk)
  2. Never make big changes - break into tiny steps
  3. Never skip the test run after each change
  4. Never continue if tests fail - fix or rollback first
  5. Never assume - when in doubt, ask
What NOT to Do
  • Don't combine refactoring with feature additions
  • Don't refactor during production emergencies
  • Don't refactor code you don't understand
  • Don't over-engineer - keep it simple
  • Don't refactor everything at once

Quick Start Example

Scenario: Long Method with Duplication

Before:

javascript
function processOrder(order) {
  // 150 lines of code with:
  // - Duplicated validation logic
  // - Inline calculations
  // - Mixed responsibilities
}

Refactoring Steps:

  1. Ensure tests exist for processOrder()
  2. Extract validation into validateOrder()
  3. Test - should pass
  4. Extract calculation into calculateOrderTotal()
  5. Test - should pass
  6. Extract notification into notifyCustomer()
  7. Test - should pass
  8. Review - processOrder() now orchestrates 3 clear functions

After:

javascript
function processOrder(order) {
  validateOrder(order);
  const total = calculateOrderTotal(order);
  notifyCustomer(order, total);
  return { order, total };
}

References

Scripts

  • scripts/analyze-complexity.py - Analyze code complexity metrics
  • scripts/detect-smells.py - Automated smell detection

Version History

  • v1.0.0 (2025-01-15): Initial release with Fowler methodology, phased approach, user consultation points

Last Updated: August 4, 2026 Claude Code Version: 2.1.220 Sources:

© luongnv89, 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 5 other files (scripts, references) in 03-skills/refactor of luongnv89/claude-howto.

  • SKILL.md
  • references/code-smells.md
  • references/refactoring-catalog.md
  • scripts/analyze-complexity.py
  • scripts/detect-smells.py
  • templates/refactoring-plan.md

Open the folder on GitHubat commit 556af8d

Compare with similar skills

Systematic Code Refactoring 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.

Systematic Code Refactoring compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Systematic Code Refactoring this skillluongnv89/claude-howto42k—~3kAutomated safety check: PassMIT
Tech Debt Analyzerailabs-393/ai-labs-claude-skills4542 repos~3.9kAutomated safety check: PassMIT
FIXME Resolvertailcallhq/forgecode7.6k—~1.1kAutomated safety check: PassApache-2.0
DesloppifyGit-on-my-level/codex-autorunner875—~3.4kAutomated safety check: PassMIT
Code Quality Gatefengshao1227/ccg-workflow5.9k—~593Automated safety check: NotesMIT
Smell CheckZhen-Bo/smell-check239—~1.5kAutomated safety check: PassMIT

Similar skills

  • Tech Debt Analyzer

    ailabs-393/ai-labs-claude-skills

    This skill should be used when analyzing technical debt in a codebase, documenting code quality issues, creating technical debt registers, or assessing code maintainability.

    454 GitHub starsUsed in 2 repos~3.9k tokens
    DevelopmentAuto-check passed
  • FIXME Resolver

    tailcallhq/forgecode

    Finds every FIXME comment in a codebase, groups related ones across files into one task, implements the work they describe and removes the comments once it is done.

    7.6k GitHub stars~1.1k tokensUpdated today
    DevelopmentAuto-check passed
  • Desloppify

    Git-on-my-level/codex-autorunner

    Codebase health scanner and technical debt tracker. An agent skill from Git-on-my-level/codex-autorunner.

    875 GitHub stars~3.4k tokensUpdated 6 days ago
    DevelopmentAuto-check passed
  • Code Quality Gate

    fengshao1227/ccg-workflow

    Scans code for complexity, long functions, duplicated blocks, naming problems and code smells with a Node script, then reports and suggests refactors.

    5.9k GitHub stars~593 tokensUpdated 22 days ago
    DevelopmentAuto-check: notes
  • Smell Check

    Zhen-Bo/smell-check

    Runs a smell-first audit on a user-chosen path set: measures structure metrics, applies a named size profile, and reports code smells and test smells with evidence strength.

    239 GitHub stars~1.5k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • A three-part cleanup guided by jscpd: measure health, then fix duplicated code, remove dead code and simplify the most complex files, finishing by re-measuring the score.

    6.3k GitHub stars~2.5k tokensUpdated today
    DevelopmentAuto-check passed

More from luongnv89/claude-howto

All 25 skills in this repo
  • Code Refactoring Workflow

    luongnv89/claude-howto

    Guides systematic, test-backed refactoring in the style of Martin Fowler, moving through research, planning and small incremental changes with your approval at each phase.

    42k GitHub stars~3.1k tokensUpdated 7 days ago
    Auto-check passed
  • Blog Post Drafting

    luongnv89/claude-howto

    Guides drafting a blog post from an idea and optional source material: research, brainstorming, outlining and version-tracked drafts, with user approval at each step.

    42k GitHub stars~2.1k tokensUpdated 7 days ago
    Auto-check passed
  • Brand Voice Guide

    luongnv89/claude-howto

    Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, public-facing content, or when…

    42k GitHub stars~609 tokensUpdated 7 days ago
    Auto-check passed
  • Code Review Specialist

    luongnv89/claude-howto

    Reviews code for security, performance, quality and maintainability, using a checklist, a finding template and two metrics scripts.

    42k GitHub stars~764 tokensUpdated 7 days ago
    Auto-check passed
  • Claude Code Skill Assessment

    luongnv89/claude-howto

    Runs a quick or deep quiz on Claude Code skills, scores ten feature areas and generates a personalized learning path with prioritized next steps.

    42k GitHub stars~5.5k tokensUpdated 7 days ago
    Auto-check passed
  • Claude Code Lesson Quiz

    luongnv89/claude-howto

    Quizzes a learner on one lesson of the Claude Code tutorial with ten questions, scores the answers and points out weak spots.

    42k GitHub stars~2.3k tokensUpdated 7 days ago
    Auto-check passed

Categories

Questions about Systematic Code Refactoring

What does Systematic Code Refactoring do?

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. The skill is built on five principles: external behavior stays the same, changes are small, tests are the safety net, refactoring is ongoing, and you approve each phase. Phase 1 is research and analysis.

When should I use Systematic Code Refactoring?

Systematic Code Refactoring fits situations like: cleaning up a tangled module without changing its behavior; reducing technical debt in legacy code; finding and removing code smells.

How do I install Systematic Code Refactoring in Claude Code?

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

How do I install Systematic Code Refactoring in Codex?

Run `npx skills add luongnv89/claude-howto --skill refactor -a codex`. Or copy the skill folder (03-skills/refactor in luongnv89/claude-howto) into .agents/skills/refactor in your project. Codex loads it when a task matches its description.

Can I use Systematic Code Refactoring 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 luongnv89/claude-howto --skill refactor -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/refactor, .gemini/skills/refactor, .github/skills/refactor and .opencode/skills/refactor in your project.

What does Systematic Code Refactoring need to run?

Going by SKILL.md and its folder, Systematic Code Refactoring needs Python for the scripts in its folder and the command-line tools its instructions call (npm, pytest, python and mvn). Our summary lists: A way to run the project's tests; Python, for the bundled `.py` analysis scripts.

Does Systematic Code Refactoring access the network?

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

Is Systematic Code Refactoring 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. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Systematic Code Refactoring use?

Systematic Code Refactoring is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Systematic Code Refactoring use?

About 3k tokens (SKILL.md is roughly 12k 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 9.5k tokens, read only when the agent opens those files.

What are the alternatives to Systematic Code Refactoring?

Skills that share tags, products or a category with Systematic Code Refactoring: Tech Debt Analyzer (ailabs-393/ai-labs-claude-skills, 454 stars), FIXME Resolver (tailcallhq/forgecode, 7.6k stars), Desloppify (Git-on-my-level/codex-autorunner, 875 stars) and Code Quality Gate (fengshao1227/ccg-workflow, 5.9k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Systematic Code Refactoring?

luongnv89 (a GitHub user) maintains it in luongnv89/claude-howto, which has 41,764 GitHub stars. The repository holds 25 skills in this directory. The repository was last updated on September 30, 2026.

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