Refactoring
Skill2 starsChanged 6 months agoMITView on GitHub
This skill should be used when the user asks to "refactor code", "rename function", "extract method", "reduce complexity", "migrate code", "code migration", "modernize code", "split class", "move code", or mentions code restructuring and refactoring operations.
58 other projects use a version of this.
Adopted by
Most recently taken up by
- ishandutta2007/Awesome-Claude-Skillstheir own version, first seen Nov 8, 2026
- larchanka/skillstheir own version, first seen Nov 8, 2026
- REPOZY/superpowers-optimizedtheir own version, first seen Nov 8, 2026
- nisarth/claude-skills-storetheir own version, first seen Nov 8, 2026
- ericwang200608-beep/LANYANT-Skillstheir own version, first seen Nov 8, 2026
- AnyOrgName/php-skillstheir own version, first seen Nov 8, 2026
Used with
Projects with it also use ci-cd, dependency-management and 9 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
JohnJBorenSkillci-cd
CI/CD pipeline design, GitHub Actions, testing automation, and deployment strategies
Also in 5 projects that use this
dkprogSkilldependency-management
Apply when wiring dependencies, integrating external services, or designing interfaces between modules. Ensures loose coupling through dependency injection, interface segregation, and proper abstraction boundaries.
Also in 3 projects that use this
javalenciacaiSkillmulti-agent-orchestration
Design and coordinate multi-agent systems where specialized agents work together to solve complex problems. Covers agent communication, task delegation, workflow orchestration, and result aggregation. Use when building coordinated agent teams, complex workflows, or systems requiring specialized expertise across domains.
Also in 3 projects that use this
harrissohail6Skilldatabase-design
Database schema design and SQL best practices. Use when designing tables, writing queries, or optimizing database performance.
Also in 5 projects that use this
MicrosoftSkillerror-handling
统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。
Also in 7 projects that use this
klauswgSkillperformance
Optimize web performance for faster loading and better user experience. Use when asked to "speed up my site", "optimize performance", "reduce load time", "fix slow loading", "improve page speed", or "performance audit".
Also in 7 projects that use this
Other versions58 projects use a version of this.
Word for word · 1
- tmcfarlane/team-avatar★ 112100% same
Edited · 0
None found.
Wrote their own version · 57
- handsontable/handsontable★ 22ksame name
- ciembor/agent-rules-books★ 2.8ksame name
- hitobito/hitobito★ 485same name
- databrickslabs/ontobricks★ 457same name
- DevelopersGlobal/ai-agent-skills★ 216same name
- REPOZY/superpowers-optimized★ 146same name
- extra-org/extra★ 119same name
- larchanka/skills★ 50same name
- nimadorostkar/Claude-Skills-collection★ 33same name
- dan-the-dev/xp-developer-skills★ 31same name
47 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository16 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/orchestrator.mdcCursor rule
- architectSkill
- codebase-searchSkill
- debuggingSkill
- design-patterns-implementationSkill
- documentation-writingSkill
- Frontend BuilderSkill
- mgrep-code-searchSkill
- planningSkill
- refactoring-patternsSkill
- technical-roadmap-planningSkill
- vercel-composition-patternsSkill
- vercel-react-best-practicesSkill
- web-design-guidelinesSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
20 rules. 0 are common, 20 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 52 edited versions we read keep these.
20
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 19
Find all references: Search for all usages
- Distinctive: line 22
Perform rename: Update all occurrences
- Distinctive: line 23
Verify: Run tests, check imports
- Distinctive: line 40
Update docstrings mentioning the old name
- Distinctive: line 41
Update comments referencing the name
- Distinctive: line 44
Consider deprecation period for public APIs
- Distinctive: line 62
Create new function with clear name
- Distinctive: line 64
Add tests for new function
- Distinctive: line 214
Create compatibility layer: If gradual migration
- Distinctive: line 215
Migrate in phases: Start with low-risk areas
- Distinctive: line 216
Maintain tests: Ensure behavior preserved
- Distinctive: line 239
Ensure test coverage: Add tests if missing
- Distinctive: line 240
Run tests: Verify green baseline
- Distinctive: line 242
Run tests again: Verify still green
- Distinctive: line 318
When refactoring public APIs:
- Distinctive: line 320
Add deprecation warnings first
- Distinctive: line 323
Remove after deprecation period
- Distinctive: line 327
When refactoring data models:
- Distinctive: line 330
Test migrations on copy of data
- Distinctive: line 348
test-coverage skill: Ensure test coverage
“Common” is measured: kept by at least 6 in 10 of the 52 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Refactoring
Comprehensive refactoring skill for safe code restructuring, migrations, and modernization.
Core Capabilities
Safe Renaming
Rename identifiers across the codebase:
Rename workflow:
- Find all references: Search for all usages
- Identify scope: Module-local, package-wide, or public API
- Check dependencies: External code that might break
- Perform rename: Update all occurrences
- Verify: Run tests, check imports
Search patterns:
# Find all references to a function
grep -rn "function_name" --include="*.py"
# Find class usages
grep -rn "ClassName" --include="*.py"
# Find imports
grep -rn "from .* import.*function_name" --include="*.py"Renaming considerations:
- Update docstrings mentioning the old name
- Update comments referencing the name
- Update configuration files
- Update tests
- Consider deprecation period for public APIs
Method Extraction
Extract code into separate functions:
When to extract:
- Code block is too long (> 20 lines)
- Code is duplicated elsewhere
- Code has a clear single purpose
- Code can be tested independently
Extraction process:
- Identify the code block to extract
- Determine inputs (parameters)
- Determine outputs (return values)
- Create new function with clear name
- Replace original code with function call
- Add tests for new function
Before:
def process_order(order):
# Validate order (candidate for extraction)
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Invalid total")
for item in order.items:
if item.quantity <= 0:
raise ValueError("Invalid quantity")
# Process payment
payment_result = gateway.charge(order.total)
return payment_resultAfter:
def validate_order(order: Order) -> None:
"""Validate order has valid items and total."""
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Invalid total")
for item in order.items:
if item.quantity <= 0:
raise ValueError("Invalid quantity")
def process_order(order: Order) -> PaymentResult:
validate_order(order)
return gateway.charge(order.total)Class Splitting
Split large classes into focused components:
When to split:
- Class has multiple responsibilities
- Class has > 500 lines
- Groups of methods work on different data
- Testing requires excessive mocking
Splitting strategies:
Extract class:
# Before: God class
class OrderManager:
def create_order(self): ...
def validate_order(self): ...
def calculate_tax(self): ...
def calculate_shipping(self): ...
def send_confirmation_email(self): ...
def send_shipping_notification(self): ...
# After: Focused classes
class OrderService:
def create_order(self): ...
def validate_order(self): ...
class PricingService:
def calculate_tax(self): ...
def calculate_shipping(self): ...
class NotificationService:
def send_confirmation_email(self): ...
def send_shipping_notification(self): ...Complexity Reduction
Reduce cyclomatic complexity:
Replace conditionals with polymorphism:
# Before: Complex switch
def calculate_price(product_type, base_price):
if product_type == "physical":
return base_price + shipping_cost
elif product_type == "digital":
return base_price
elif product_type == "subscription":
return base_price * 12 * 0.9
else:
raise ValueError("Unknown type")
# After: Polymorphism
class Product(ABC):
@abstractmethod
def calculate_price(self, base_price): ...
class PhysicalProduct(Product):
def calculate_price(self, base_price):
return base_price + self.shipping_cost
class DigitalProduct(Product):
def calculate_price(self, base_price):
return base_price
class Subscription(Product):
def calculate_price(self, base_price):
return base_price * 12 * 0.9Extract guard clauses:
# Before: Nested conditionals
def process(data):
if data:
if data.is_valid:
if data.is_ready:
return do_processing(data)
return None
# After: Guard clauses
def process(data):
if not data:
return None
if not data.is_valid:
return None
if not data.is_ready:
return None
return do_processing(data)Code Migration
Migrate code between patterns or versions:
Migration types:
- Python 2 to 3
- Sync to async
- ORM migrations
- API version upgrades
- Framework migrations
Migration workflow:
- Assess scope: What needs to change
- Create compatibility layer: If gradual migration
- Migrate in phases: Start with low-risk areas
- Maintain tests: Ensure behavior preserved
- Remove old code: Clean up after migration
Example: Sync to Async
# Before: Synchronous
def fetch_user(user_id: int) -> User:
response = requests.get(f"/users/{user_id}")
return User.from_dict(response.json())
# After: Asynchronous
async def fetch_user(user_id: int) -> User:
async with aiohttp.ClientSession() as session:
async with session.get(f"/users/{user_id}") as response:
data = await response.json()
return User.from_dict(data)Refactoring Workflow
Safe Refactoring Process
- Ensure test coverage: Add tests if missing
- Run tests: Verify green baseline
- Make small change: One refactoring at a time
- Run tests again: Verify still green
- Commit: Save progress
- Repeat: Continue with next change
Pre-Refactoring Checklist
[ ] Tests exist for affected code
[ ] All tests pass
[ ] Change is well understood
[ ] Impact scope identified
[ ] Rollback plan existsPost-Refactoring Verification
[ ] All tests still pass
[ ] No new linting errors
[ ] Type checking passes
[ ] Functionality unchanged
[ ] Performance acceptableCommon Refactorings
Remove Dead Code
# Find and remove:
# - Unused imports
# - Unused variables
# - Unreachable code
# - Commented-out code
# - Deprecated functions
# Tools:
# - vulture (Python)
# - autoflake (Python)
# - eslint (JavaScript)Simplify Expressions
# Before
if condition == True:
return True
else:
return False
# After
return conditionIntroduce Explaining Variables
# Before
if user.age >= 18 and user.country in ['US', 'CA'] and user.verified:
allow_purchase()
# After
is_adult = user.age >= 18
is_supported_country = user.country in ['US', 'CA']
is_verified = user.verified
can_purchase = is_adult and is_supported_country and is_verified
if can_purchase:
allow_purchase()Safety Guidelines
Breaking Changes
When refactoring public APIs:
- Add deprecation warnings first
- Maintain backwards compatibility
- Document migration path
- Remove after deprecation period
Database Migrations
When refactoring data models:
- Create migration scripts
- Test migrations on copy of data
- Plan for rollback
- Consider zero-downtime migrations
Performance Impact
After refactoring:
- Run performance benchmarks
- Compare with baseline
- Profile if regression found
- Optimize if necessary
Integration
Coordinate with other skills:
- code-quality skill: Measure improvement
- test-coverage skill: Ensure test coverage
- architecture-review skill: Validate structural changes
- git-workflows skill: Proper commit messages for refactors
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

