code-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.
Install
mkdir -p .claude/skills/code-refactor && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5521" && unzip -o skill.zip -d .claude/skills/code-refactor && rm skill.zipInstalls to .claude/skills/code-refactor
About this skill
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
- Behavior Preservation: External behavior must remain unchanged
- Small Steps: Make tiny, testable changes
- Test-Driven: Tests are the safety net
- Continuous: Refactoring is ongoing, not a one-time event
- 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:
- Scope: Which files/modules/functions need refactoring?
- Goals: What problems are you trying to solve? (readability, performance, maintainability)
- Constraints: Are there any areas that should NOT be changed?
- Timeline pressure: Is this blocking other work?
- 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
-
Check for existing tests
# Look for test files find . -name "*test*" -o -name "*spec*" | head -20 -
Run existing tests
# JavaScript/TypeScript npm test # Python pytest -v # Java mvn test -
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:
- Write tests first (recommended)
- Add tests incrementally during refactoring
- 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:
- Write failing test (red)
- Make it pass (green)
- 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
| Smell | Signs | Impact |
|---|---|---|
| Long Method | Methods > 30-50 lines | Hard to understand, test, maintain |
| Duplicated Code | Same logic in multiple places | Bug fixes needed in multiple places |
| Large Class | Class with too many responsibilities | Violates Single Responsibility |
| Feature Envy | Method uses another class's data more | Poor encapsulation |
| Primitive Obsession | Overuse of primitives instead of objects | Missing domain concepts |
| Long Parameter List | Methods with 4+ parameters | Hard to call correctly |
| Data Clumps | Same data items appearing together | Missing abstraction |
| Switch Statements | Complex switch/if-else chains | Hard to extend |
| Speculative Generality | Code "just in case" | Unnecessary complexity |
| Dead Code | Unused code | Confusion, maintenance burden |
Analysis Steps
-
Automated Analysis (if scripts available)
python scripts/detect-smells.py <file> -
Manual Review
- Walk through code systematically
- Note each smell with location and severity
- Categorize by impact (Critical/High/Medium/Low)
-
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 Smell | Recommended Refactoring(s) |
|---|---|
| Long Method | Extract Method, Replace Temp with Query |
| Duplicated Code | Extract Method, Pull Up Method, Form Template Method |
| Large Class | Extract Class, Extract Subclass |
| Feature Envy | Move Method, Move Field |
| Primitive Obsession | Replace Primitive with Object, Replace Type Code with Class |
| Long Parameter List | Introduce Parameter Object, Preserve Whole Object |
| Data Clumps | Extract Class, Introduce Parameter Object |
| Switch Statements | Replace Conditional with Polymorphism |
| Speculative Generality | Collapse Hierarchy, Inline Class, Remove Dead Code |
| Dead Code | Remove Dead Code |
Plan Structure
Use the template at templates/refactoring-plan.md.
For each refactoring:
- Target: What code will change
- Smell: What problem it addresses
- Refactoring: Which technique to apply
- Steps: Detailed micro-steps
- Risks: What could go wrong
- 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:
-
Pre-check
- Tests are passing (green)
- Code compiles
-
Make ONE small change
- Follow the mechanics from the catalog
- Keep changes minimal
-
Verify
- Run tests immediately
- Check for compilation errors
-
If tests pass (green)
- Commit with descriptive message
- Move to next step
-
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
- Never refactor without tests (unless user explicitly acknowledges risk)
- Never make big changes - break into tiny steps
- Never skip the test run after each change
- Never continue if tests fail - fix or rollback first
- 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: L
Content truncated.
More by luongnv89
View all skills by luongnv89 →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversStreamline your team software process with Spec-Driven Development, optimizing the software development life cycle using
Streamline your software development life cycle with Spec-Driven Development: organized specs, template-driven code, and
Cairo Coder: Expert Cairo and Starknet development support, smart contract creation, and code refactoring via the Cairo
Structured Workflow guides disciplined software engineering via refactoring, feature creation, and test driven developme
Refactor enables regex-based code refactoring for bulk search-and-replace, pattern matching, and large-scale code transf
Chrome extension-based MCP server that exposes browser functionality to AI assistants. Control tabs, capture screenshots
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.