跳到主要内容

refactor 精选

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.

在 GitHub 打开

安装方式

cp -r 03-skills/refactor ~/.claude/skills/refactor

把该 skill 目录放进客户端 skills 目录。不同客户端的目录可能不同,Claude Code 默认是 ~/.claude/skills/

整仓一次性获取:git clone --depth 1 https://github.com/luongnv89/claude-howto.git

依赖与权限

  • 无需 API Key
  • 需要联网访问外部服务
  • 依赖外部命令:npm python go make
  • 以上为按正文与 frontmatter 自动推断的信号,仅供参考;安装前建议先阅读原文。
触发场景
improve code structurereduce technical debtclean up legacy

SKILL.md 正文

来源 luongnv89/claude-howto@065ab37 · 许可 MIT · 内容未修改

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
   # Look for test files
   find . -name "*test*" -o -name "*spec*" | head -20
  1. Run existing tests
   # JavaScript/TypeScript
   npm test

   # Python
   pytest -v

   # Java
   mvn test
  1. Check coverage (if available)
   # 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](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)
   python scripts/detect-smells.py <file>
  1. Manual Review
  • Walk through code systematically
  • Note each smell with location and severity
  • Categorize by impact (Critical/High/Medium/Low)
  1. 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](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](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

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
  1. Make ONE small change
  • Follow the mechanics from the catalog
  • Keep changes minimal
  1. Verify
  • Run tests immediately
  • Check for compilation errors
  1. If tests pass (green)
  • Commit with descriptive message
  • Move to next step
  1. 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:

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:

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:

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

References

  • [Code Smells Catalog](references/code-smells.md) - Complete list of code smells
  • [Refactoring Catalog](references/refactoring-catalog.md) - Refactoring techniques
  • [Refactoring Plan Template](templates/refactoring-plan.md) - Planning template

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:

  • https://code.claude.com/docs/en/skills

Compatible Models: Claude Fable 5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 4.5

质量与来源

所属仓库
luongnv89/claude-howto
仓库星标
4.2 万
最近更新
昨天
采集时间
今天
commit
065ab3734f64
内容指纹
sha256:459b8b4aacdcb76
文件路径
03-skills/refactor/SKILL.md

同仓库其它 Skill

查看全部 25 个
lesson-quiz
Test a learner on a single Claude Code tutorial lesson (01-10) with 10 questions, scoring answers and flagging weak spots. Use before, during, or after a lesson. Don't use for whole-tutorial assessment or explaining a topic instead of testing it.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
self-assessment
Comprehensive Claude Code self-assessment and learning path advisor. Runs a multi-category quiz covering 10 feature areas, produces a detailed skill profile with per-topic scores, identifies specific gaps, and generates a personalized learning path with prioritized next steps. Use when asked to "assess my level", "take the quiz", "find my level", "where should I start", "what should I learn next", "check my skills", "skill check", or "level up".
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
blog-draft
Draft a blog post from ideas and resources. Use when users want to write a blog post, create content from research, or draft articles. Guides through research, brainstorming, outlining, and iterative drafting with version control.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
brand-voice
Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, public-facing content, or when users mention brand voice, tone, or writing style.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
claude-md
Create or update CLAUDE.md files following best practices for optimal AI agent onboarding
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
code-review-specialist
Comprehensive code review with security, performance, and quality analysis. Use when users ask to review code, analyze code quality, evaluate pull requests, or mention code review, security analysis, or performance optimization.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端

相似 Skill

更多「写作」
interview-prep
Prepares the user for a specific interview from their real experience. Builds a story bank in Situation/Task/Action/Result/Reflection form mapped to the competencies the role and company test (such as Amazon's Leadership Principles), writes a cited company and role brief from public sources, predicts questions per round, drafts opener, why-us, weakness and salary answers, prepares questions to ask and a logistics checklist, and runs a post-interview debrief. Use when the user says "help me prepare for my interview", "I have an interview tomorrow" or "in 2 hours", "build my story bank", "STAR stories", "interviewing as a career changer", "what will they ask me", "how do I answer tell me about yourself", "questions to ask the interviewer", "research the company" or "debrief my interview". Uses Reactive Resume MCP tools when connected. For scored role-play practice, mock-interview; for thank-you notes and tracking, job-application-manager; for a salary number, offers or negotiation, offer-negotiation.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
job-application-manager
Runs the job-search pipeline. Adds jobs from a link or pasted posting, keeps stages and dates accurate, sets follow-ups, runs a weekly review (stale applications, next actions, funnel stats), records the exact resume version sent, and drafts networking, LinkedIn, referral, recruiter-reply, follow-up, thank-you, status-check, expedite and withdrawal messages without sending them. Use when the user says "add this job to my tracker", "I applied", "log my interview", "I got rejected", "I was ghosted", "log my offer", "track my applications", "do my weekly review", "what should I follow up on", "write a thank-you note", "message this recruiter", "ask for a referral", "withdraw my application", or wants a job-search spreadsheet. Works with a Markdown/CSV tracker or Reactive Resume MCP tools. Not for resume work (resume-tailor, resume-bullet-writer, resume-content-guide), interview prep or practice (interview-prep, mock-interview), or judging, negotiating, accepting or declining an offer (offer-negotiation).
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
mock-interview
Runs a mock interview for a specific job description. Plays the interviewer in a chosen round (recruiter screen, hiring manager, behavioral, coding, system design, case, product sense, panel), persona and difficulty; asks one question at a time, probes vague answers, and gives quote-backed rubric scores after each answer (coach mode) or at the end (realistic). Model answers use only the user's real experience. Use when the user says "mock interview me", "interview me for this job", "practice interview", "pretend you're the interviewer", "grill me for this role", "run a behavioral round", "quick recruiter screen", "hiring-manager mock", "system design mock" or "case interview practice". With Reactive Resume MCP it reads the application and stories and logs the session. For a story bank, company brief, questions to ask or a real-interview debrief, interview-prep; for scheduling or thank-you notes, job-application-manager; for fixing the resume, resume-tailor; for negotiation practice, offer-negotiation.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
offer-negotiation
Evaluates and negotiates job offers. Decodes base, bonus, equity, sign-on, level and terms with unknowns kept unknown and each offer in its own currency, benchmarks against checkable pay data, finds true leverage, drafts one counter as email and call script, role-plays the recruiter, and handles the salary-expectations number, deadlines and extensions, "best and final", competing offers, counteroffers and written acceptance or decline. Country-aware (India CTC, 13th-month pay, public-sector scales). Use when the user says "I got an offer of...", "is this offer good", "should I negotiate", "how do I counter", "compare my offers", "what is my equity worth", "they asked my salary expectations", "they want an answer by Friday", "can I ask for more time", "should I accept" or "practice the negotiation call". Uses Reactive Resume MCP tools when connected. For logging the offer, its deadline and withdrawal notes, job-application-manager; for other interview answers, interview-prep.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
resume-builder
Builds a complete resume from scratch as Reactive Resume JSON that conforms to the schema and imports at https://rxresu.me. Asks for each missing detail instead of inventing it, then produces valid JSON (UUIDs, HTML descriptions, template and layout). Use when the user wants to create, build or generate a new resume, turn their work history into Reactive Resume JSON, or asks about the Reactive Resume schema, sections, templates or layout. For what belongs on a resume or a resume audit use resume-content-guide; for rewriting bullets, resume-bullet-writer; for fitting one job posting, resume-tailor; for tracking applications, job-application-manager; for interviews, interview-prep or mock-interview.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
resume-bullet-writer
Turns resume duties into truthful impact bullets. Questions the user role by role to dig out achievements, asks for real numbers or honest ranges (never invents them), and writes concise bullets in XYZ, CAR, scope or qualitative form. Use when the user says "rewrite my bullets", "make this bullet stronger", "quantify my resume", "turn my duties into achievements", "improve my experience section", "my resume sounds boring", "I don't have any numbers", pastes resume lines for feedback, or works in a low-number job (nursing, teaching, care, trades, admin, creative). With the Reactive Resume MCP server connected, it edits experience, project, volunteer and education descriptions with apply_resume_patch after the user approves. Use resume-content-guide instead for which sections or details belong and for summaries or headlines, resume-tailor to fit one job posting, interview-prep or mock-interview for interview stories and practice, and resume-builder to build a resume from scratch.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI