Agent skill

Systematic Code Refactoring

by luongnv89 in luongnv89/claude-howto

Walks through code refactoring in phases you confirm, following Martin Fowler's method: research, test check, smell detection, planning and small safe steps.

MITAuto-check passedDevelopment

SKILL.md written in Chinese; this summary is our English description.

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/zh/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
~1.5k tokens
SKILL.md length
441 words
Files
4 (incl. references)
Skills in repo
25
Repo updated
First seen
Licence
MIT

At a glance

Walks through code refactoring in phases you confirm, following Martin Fowler's method: research, test check, smell detection, planning and small safe steps.

  • Works in 5 steps: 保持行为不变:外部行为必须保持一致 → 小步前进:每次只做很小、可测试的改动 → 测试驱动:测试是安全网 → …
  • Refactoring a module that has grown hard to maintain
  • SKILL.md covers 核心原则, 工作流程总览, 阶段 1:研究与分析 and 阶段 2:测试覆盖评估, plus 4 more sections
  • Calls npm, pytest and python

What it does

The skill follows Martin Fowler's approach to refactoring: keep external behavior unchanged, make small testable changes, use tests as the safety net, treat refactoring as ongoing work and get your confirmation at each phase. Phase one asks about scope, goals, constraints, time pressure and test status, reads the code, notes dependencies and TODO or FIXME debt markers, and asks for approval before continuing.

Phase two looks for existing tests, runs them and checks coverage. If tests are missing, the agent offers to write them first, to add them along the way or to continue at your risk, and it stops when tests fail. Phase three scans for code smells such as long functions, duplicated code, large classes, long parameter lists and dead code, ranks them by severity and asks you to confirm priorities. Phase four picks refactorings from a catalog and builds a plan. Reference files hold the smell and refactoring catalogs and a template holds the plan; the excerpt ends in phase four.

When your agent uses it

  • Refactoring a module that has grown hard to maintain
  • Cleaning up code smells before adding a new feature
  • Reducing technical debt in steps you approve at each phase

Example prompts

  • “Refactor the order-processing module, ask me about scope first and check the tests.”
  • “Find code smells in src/billing and rank them by severity.”
  • “Make a refactoring plan for the oversized UserService class using small safe steps.”

Workflow steps

5 steps, taken from the first numbered list in SKILL.md.

  1. 保持行为不变:外部行为必须保持一致
  2. 小步前进:每次只做很小、可测试的改动
  3. 测试驱动:测试是安全网
  4. 持续进行:重构是长期过程,不是一次性任务
  5. 协作确认:每个阶段都需要用户确认

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

    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

    No URLs in SKILL.md. Its commands use npm, which can reach the network depending on how they are called.

    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 1.5k tokens when it runs, and up to ~11k if it reads all its reference files. Until then it costs about 32 tokens; SKILL.md has 441 words of instructions outside code blocks.

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

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 luongnv89/claude-howto at commit 556af8d, republished under its MIT licence (© luongnv89). 441 words, ~1,505 tokens.

Download SKILL.mdSave it as .claude/skills/refactor/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
refactor
description
基于 Martin Fowler 方法论的系统化代码重构 skill。适用于用户请求重构代码、改进代码结构、减少技术债、清理旧代码、消除 code smell 或提升可维护性时。这个 skill 采用分阶段、带研究与计划的安全增量实施方式。

代码重构 Skill

这是一个基于 Martin Fowler《Refactoring: Improving the Design of Existing Code》(第 2 版)的系统化代码重构方法。这个 skill 强调安全、渐进的修改,并由测试提供保障。

“重构是在不改变软件外部行为的前提下,改进其内部结构的过程。” — Martin Fowler

核心原则

  1. 保持行为不变:外部行为必须保持一致
  2. 小步前进:每次只做很小、可测试的改动
  3. 测试驱动:测试是安全网
  4. 持续进行:重构是长期过程,不是一次性任务
  5. 协作确认:每个阶段都需要用户确认

工作流程总览

阶段 1:研究与分析
    ↓
阶段 2:测试覆盖评估
    ↓
阶段 3:识别代码异味
    ↓
阶段 4:创建重构计划
    ↓
阶段 5:增量实施
    ↓
阶段 6:评审与迭代

阶段 1:研究与分析

目标
  • 理解代码库结构和用途
  • 确定重构范围
  • 收集业务需求背景
先向用户确认的问题

开始前先确认:

  1. 范围:哪些文件 / 模块 / 函数需要重构?
  2. 目标:你想解决什么问题?(可读性、性能、可维护性)
  3. 约束:有哪些区域不能改?
  4. 时间压力:这是否阻塞了其他工作?
  5. 测试状态:是否已有测试?是否通过?
行动
  • 阅读并理解目标代码
  • 识别依赖和集成点
  • 记录当前架构
  • 标记已有技术债迹象(TODO、FIXME)
输出

向用户汇报:

  • 代码结构总结
  • 识别出的问题区域
  • 初步建议
  • 请求继续执行的批准

阶段 2:测试覆盖评估

为什么测试重要

“没有测试的重构,就像没有安全带就开车。” — Martin Fowler

测试是安全重构的关键前提。没有测试,很容易引入 bug。

评估步骤
  1. 检查现有测试

    bash
    # 查找测试文件
    find . -name "*test*" -o -name "*spec*" | head -20
  2. 运行现有测试

    bash
    # JavaScript / TypeScript
    npm test
    
    # Python
    pytest -v
    
    # Java
    mvn test
  3. 检查覆盖率(如果可用)

    bash
    # JavaScript
    npm run test:coverage
    
    # Python
    pytest --cov=.
决策点:询问用户

如果测试存在且通过:

  • 进入阶段 3

如果测试缺失或不完整: 给出选项:

  1. 先写测试(推荐)
  2. 在重构过程中逐步补测试
  3. 不写测试直接继续(有风险,需要用户确认)

如果测试失败:

  • 停止。先修复失败测试再重构
  • 问用户:是否先修测试?
测试编写建议(如需要)

对每个要重构的函数,测试应覆盖:

  • 正常路径
  • 边界情况(空输入、null、边界值)
  • 错误场景(非法输入、异常)

使用“红-绿-重构”循环:

  1. 写失败测试(红)
  2. 让它通过(绿)
  3. 再重构

阶段 3:识别代码异味

什么是代码异味?

代码深层问题的表面症状。它们不一定是 bug,但说明代码设计可能有问题。

常见异味清单

完整目录见 references/code-smells.md。

快速参考
异味迹象影响
长函数函数超过 30-50 行难以理解、测试和维护
重复代码多处出现相同逻辑修复需要改多处
大类类承担了太多职责违反单一职责原则
Feature Envy一个方法更多依赖别的类的数据封装性差
基础类型沉迷过度使用基础类型而不是对象缺少领域概念
长参数列表方法参数超过 4 个调用困难
数据泥团一组数据总是一起出现缺少抽象
switch 语句复杂的 switch / if-else 链难以扩展
臆想泛化“以防未来需要”提前设计不必要的复杂度
死代码未使用的代码造成困惑和维护负担
分析步骤
  1. 自动分析(如果有脚本)

    bash
    python scripts/detect-smells.py <file>
  2. 人工审查

    • 系统地走读代码
    • 记录每个异味的位置和严重性
    • 按影响分类(Critical / High / Medium / Low)
  3. 优先级排序 优先关注会:

    • 阻塞当前开发的异味
    • 导致 bug 或混淆的异味
    • 影响最常变更代码路径的异味
输出:异味报告

向用户呈现:

  • 识别出的异味及位置
  • 每项的严重性评估
  • 建议的优先级顺序
  • 请求用户确认优先级

阶段 4:创建重构计划

选择重构方式

针对每个异味,从目录中选择合适的重构手法。

完整列表见 references/refactoring-catalog.md。

异味到重构的映射
代码异味推荐重构
长函数Extract Method、Replace Temp with Query
重复代码Extract Method、Pull Up Method、Form Template Method
大类Extract Class、Extract Subclass
Feature EnvyMove Method、Move Field
基础类型沉迷Replace Primitive with Object、Replace Type Code with Class
长参数列表Introduce Parameter Object、Preserve Whole Object
数据泥团Extract Class、Introduce Parameter Object
switch 语句Replace Conditional with Polymorphism
臆想泛化Collapse Hierarchy、Inline Class、Remove Dead Code
死代码Remove Dead Code
Show full SKILL.md (195 more words)Show less
计划结构

使用 templates/refactoring-plan.md 里的模板。

每项重构都要写明:

  1. Target:将修改哪些代码
  2. Smell:解决什么问题
  3. Refactoring:采用哪种手法
  4. Steps:详细微步骤
  5. Risks:可能出什么问题
  6. Rollback:如何回退
分阶段方法

关键:重构必须分阶段推进。

阶段 A:快速收益(低风险,高价值)

  • 重命名变量以提升清晰度
  • 提取明显重复的代码
  • 删除死代码

阶段 B:结构改进(中风险)

  • 从长函数中提取方法
  • 引入参数对象
  • 把方法移动到更合适的类

阶段 C:架构改动(高风险)

  • 用多态替代条件分支
  • 提取类
  • 引入设计模式
决策点:把计划展示给用户

在开始实施前:

  • 展示完整重构计划
  • 解释每个阶段及其风险
  • 获得每个阶段的明确批准
  • 询问:“是否继续执行阶段 A?”

阶段 5:增量实施

黄金法则

“修改 → 测试 → 通过?→ 提交 → 下一步”

实施节奏

对每一步重构:

  1. 预检查

    • 测试通过(绿色)
    • 代码能编译
  2. 只做一个小改动

    • 按目录中的具体操作进行
    • 保持改动最小化
  3. 验证

    • 立刻运行测试
    • 检查编译错误
  4. 如果测试通过(绿色)

    • 用描述清晰的提交信息提交
    • 继续下一步
  5. 如果测试失败(红色)

    • 立刻停止
    • 撤销改动
    • 分析原因
    • 如有疑问,询问用户
提交策略

每次提交都应当:

  • 原子性:只包含一个逻辑改动
  • 可回滚:容易撤销
  • 描述清楚:提交信息明确

示例提交信息:

refactor: 从 processOrder() 中提取 calculateTotal()
refactor: 将 'x' 重命名为 'customerCount' 以提升清晰度
refactor: 删除未使用的 validateOldFormat() 方法
进度汇报

每个子阶段完成后,向用户汇报:

  • 做了哪些改动
  • 测试是否仍通过
  • 遇到了什么问题
  • 询问:“继续下一批吗?”

阶段 6:评审与迭代

重构后检查清单
  • 所有测试通过
  • 没有新的警告 / 错误
  • 代码编译成功
  • 行为没有变化(手动验证)
  • 必要时已更新文档
  • 提交历史干净
指标对比

重构前后运行复杂度分析:

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

展示改进:

  • 代码行数变化
  • 圈复杂度变化
  • 可维护性指标变化
用户评审

向用户展示最终结果:

  • 所有变更摘要
  • 重构前后代码对比
  • 指标改善情况
  • 剩余技术债
  • 询问:“你对这些改动满意吗?”
下一步

和用户讨论:

  • 还要处理哪些异味?
  • 是否安排下一次重构?
  • 是否把类似修改应用到其他地方?

重要指南

何时暂停并询问

遇到以下情况时,务必暂停并和用户确认:

  • 不确定业务逻辑
  • 改动可能影响外部 API
  • 测试覆盖不足
  • 需要做重大的架构决策
  • 风险上升
  • 遇到意外复杂性
安全规则
  1. 没有测试不要重构(除非用户明确确认风险)
  2. 不要做大改动,拆成小步
  3. 每次改动后都不要跳过测试
  4. 测试失败就不要继续,先修复或回滚
  5. 不要臆测,不确定就问
不要做什么
  • 不要把重构和新功能混在一起
  • 不要在生产事故期间做重构
  • 不要重构你看不懂的代码
  • 不要过度设计,保持简单
  • 不要一次性重构所有内容

快速上手示例

场景:长函数 + 重复逻辑

重构前:

javascript
function processOrder(order) {
  // 150 行代码,包含:
  // - 重复验证逻辑
  // - 内联计算
  // - 多种职责混杂
}

重构步骤:

  1. 确认测试存在,覆盖 processOrder()
  2. 提取 验证逻辑为 validateOrder()
  3. 测试 - 应该通过
  4. 提取 计算逻辑为 calculateOrderTotal()
  5. 测试 - 应该通过
  6. 提取 通知逻辑为 notifyCustomer()
  7. 测试 - 应该通过
  8. 评审 - processOrder() 现在只负责串联 3 个清晰函数

重构后:

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

参考资料

脚本

  • scripts/analyze-complexity.py - 分析代码复杂度指标
  • scripts/detect-smells.py - 自动检测 code smell

版本历史

  • v1.0.0 (2025-01-15):首次发布,包含 Fowler 方法论、分阶段流程和用户确认点

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

  • SKILL.md
  • references/code-smells.md
  • references/refactoring-catalog.md
  • 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—~1.5kAutomated 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 today
    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.4k GitHub stars~2.5k tokensUpdated today
    DevelopmentAuto-check passed

More from luongnv89/claude-howto

All 25 skills in this repo
  • 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
    Auto-check passed
  • 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

Categories

Questions about Systematic Code Refactoring

What does Systematic Code Refactoring do?

Walks through code refactoring in phases you confirm, following Martin Fowler's method: research, test check, smell detection, planning and small safe steps. The skill follows Martin Fowler's approach to refactoring: keep external behavior unchanged, make small testable changes, use tests as the safety net, treat refactoring as ongoing work and get your confirmation at each phase. Phase one asks about scope, goals, constraints, time pressure and test status, reads the code, notes dependencies and TODO or FIXME debt markers, and asks for approval before continuing.

When should I use Systematic Code Refactoring?

Systematic Code Refactoring fits situations like: refactoring a module that has grown hard to maintain; cleaning up code smells before adding a new feature; reducing technical debt in steps you approve at each phase.

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 (zh/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 (zh/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 the command-line tools its instructions call (npm, pytest, python and mvn).

Does Systematic Code Refactoring access the network?

SKILL.md contains no URLs. Its commands use npm, which can reach the network depending on how they are called. 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. Review the folder before installing.

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 1.5k tokens (SKILL.md is roughly 6k 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.1k 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,769 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.