refactoring
Skill1 starsChanged 7 months agoMITView on GitHub
Plan and execute code refactoring. Extract methods, decompose classes, apply design patterns, reduce complexity, and maintain backward compatibility throughout. Trigger with "refactor this", "this code is messy", "simplify this", "extract a function", "reduce complexity", "apply design pattern", or when the user wants to restructure code without changing behavior.
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
- ericwang200608-beep/LANYANT-Skillstheir own version, first seen Nov 8, 2026
- AnyOrgName/php-skillstheir own version, first seen Nov 8, 2026
- SWEStash/swe-workflow-skillstheir own version, first seen Nov 8, 2026
Used with
Projects with it also use ci-cd, dependency-management and 7 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
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
AWSSkillplanning
Discovers user intent and generates a structured, step-by-step plan for model customization workflows. This skill must always be activated alongside any other skill when the user's request relates to model customization — including fine-tuning, training, building, customizing, reviewing data, or getting advice on approach, regardless of domain. Do not skip this skill even if the immediate ask is narrow (e.g., reviewing data format or a single workflow step), because planning discovers the full scope of work needed. Also activate when the user wants to resume, continue, or modify an existing plan.
Also in 6 projects that use this
Other versions58 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 58
- 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
- tmcfarlane/team-avatar★ 112same name
- larchanka/skills★ 50same name
- nimadorostkar/Claude-Skills-collection★ 33same name
48 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 repository164 other files it gives its agents.
- instrument-data-to-allotropeSkill
- literature-reviewSkill
- nextflow-developmentSkill
- scientific-problem-selectionSkill
- scvi-toolsSkill
- single-cell-rna-qcSkill
- discover-brandSkill
- enforce-voiceSkill
- generate-guidelinesSkill
- csat-reportSkill
- customer-escalationSkill
- customer-researchSkill
- draft-responseSkill
- kb-articleSkill
- sentiment-analysisSkill
- ticket-triageSkill
- analyzeSkill
- build-dashboardSkill
- create-vizSkill
- data-context-extractorSkill
- data-modelingSkill
- data-pipelineSkill
- etl-designSkill
- explore-dataSkill
- sql-queriesSkill
- statistical-analysisSkill
- validate-dataSkill
- write-querySkill
- accessibility-reviewSkill
- component-librarySkill
- design-critiqueSkill
- design-handoffSkill
- design-systemSkill
- frontend-designSkill
- research-synthesisSkill
- user-researchSkill
- ux-copySkill
- wireframingSkill
- Agent DevelopmentSkill
- CLAUDE.md ManagementSkill
- MCP Server BuilderSkill
- Plugin DevelopmentSkill
- Prompt EngineeringSkill
- Skill CreatorSkill
- curriculum-designSkill
- lesson-planningSkill
- quiz-generatorSkill
- study-guideSkill
- tutoringSkill
- api-designSkill
- architectureSkill
- ci-cd-pipelineSkill
- code-reviewSkill
- database-migrationSkill
- debugSkill
- dependency-auditSkill
- deploy-checklistSkill
- documentationSkill
- error-handlingSkill
- git-workflowSkill
- The first 60 shown.
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 53 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 33
Read the target code and assess its current state:
- Distinctive: line 37
Check test coverage: Run tests and check coverage.
- Distinctive: line 39
Understand the domain: Read surrounding code and comments to understand business context.
- Distinctive: line 55
Create a step-by-step plan before making any changes:
- Distinctive: line 57
Ensure test coverage: Write missing tests for the code being refactored.
- Distinctive: line 58
Order changes by risk: Start with the safest, most mechanical refactorings.
- Distinctive: line 127
Use composition: the original class delegates to the new classes.
- Distinctive: line 186
Run tests to verify behavior is unchanged.
- Distinctive: line 188
Commit the change with a descriptive message.
- Distinctive: line 190
If tests fail after a refactoring step, revert and investigate before proceeding.
- Distinctive: line 194
After all refactoring steps are complete:
- Distinctive: line 196
Run the full test suite.
- Distinctive: line 197
Check for unused imports, dead code, or orphaned files created during refactoring.
- Distinctive: line 198
Verify that public APIs (function signatures, exports, endpoints) have not changed unless intended.
- Distinctive: line 244
Action: Read the function, identify logical sections, extract each section into a named function with clear parameters and return values, …
- Distinctive: line 257
Never refactor without tests.
- Distinctive: line 260
Commit after each successful refactoring step.
- Distinctive: line 262
Do not over-abstract. Extracting a function used only once may reduce readability rather than improve it.
- Distinctive: line 264
Use the IDE or editor's refactoring tools when available (rename symbol, extract method) as they handle all references automatically.
- Distinctive: line 265
Consider readability from the perspective of someone seeing the code for the first time.
“Common” is measured: kept by at least 6 in 10 of the 53 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
Plan and execute safe code refactoring. Identify code smells, apply proven refactoring patterns, maintain backward compatibility, and verify correctness with tests throughout the process.
Workflow
Step 1: Analyze the Current Code
Read the target code and assess its current state:
- Read the file/module: Understand what the code does, not just how it looks.
- Identify code smells: Long methods, deep nesting, duplicated code, feature envy, data clumps.
- Check test coverage: Run tests and check coverage. If coverage is low, write tests first.
- Map dependencies: What calls this code? What does it call? Use grep to find usages.
- Understand the domain: Read surrounding code and comments to understand business context.
Code smell checklist:
- Functions longer than 30 lines
- Functions with more than 4 parameters
- Cyclomatic complexity above 10
- Deeply nested conditionals (3+ levels)
- Duplicated code blocks (3+ similar blocks)
- God classes (classes doing too many things)
- Feature envy (method uses another class's data more than its own)
- Primitive obsession (using primitives instead of value objects)
- Shotgun surgery (one change requires edits in many places)
- Long switch/if-else chains on the same discriminator
Step 2: Plan the Refactoring
Create a step-by-step plan before making any changes:
- Ensure test coverage: Write missing tests for the code being refactored.
- Order changes by risk: Start with the safest, most mechanical refactorings.
- Keep changes small: Each step should be independently verifiable.
- Maintain backward compatibility: Public interfaces should not change unless explicitly planned.
Common refactoring patterns:
Extract Method — Pull a block of code into a named function:
# Before
def process_order(order):
# validate
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Negative total")
# calculate tax
tax = order.total * 0.08
if order.state == "OR":
tax = 0
# ... more code
# After
def process_order(order):
validate_order(order)
tax = calculate_tax(order)
# ... more code
def validate_order(order):
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Negative total")
def calculate_tax(order):
if order.state == "OR":
return 0
return order.total * 0.08Replace Conditional with Polymorphism:
# Before
def calculate_shipping(order):
if order.type == "standard":
return order.weight * 0.5
elif order.type == "express":
return order.weight * 1.5 + 10
elif order.type == "overnight":
return order.weight * 3.0 + 25
# After
class ShippingCalculator:
_strategies = {
"standard": lambda w: w * 0.5,
"express": lambda w: w * 1.5 + 10,
"overnight": lambda w: w * 3.0 + 25,
}
@classmethod
def calculate(cls, order):
strategy = cls._strategies.get(order.type)
if not strategy:
raise ValueError(f"Unknown shipping type: {order.type}")
return strategy(order.weight)Decompose Class — Split a god class into focused classes:
- Identify groups of related fields and methods.
- Extract each group into its own class.
- Use composition: the original class delegates to the new classes.
Replace Magic Values with Constants:
// Before
if (user.role === 3) { ... }
setTimeout(retry, 30000);
// After
const ROLE_ADMIN = 3;
const RETRY_DELAY_MS = 30_000;
if (user.role === ROLE_ADMIN) { ... }
setTimeout(retry, RETRY_DELAY_MS);Introduce Parameter Object — Group related parameters:
// Before
function createUser(name: string, email: string, age: number,
street: string, city: string, zip: string) { ... }
// After
interface Address { street: string; city: string; zip: string; }
interface CreateUserInput { name: string; email: string; age: number; address: Address; }
function createUser(input: CreateUserInput) { ... }Flatten Nested Conditionals — Use early returns (guard clauses):
// Before
function getDiscount(user) {
if (user) {
if (user.isPremium) {
if (user.yearsActive > 5) {
return 0.3;
} else {
return 0.15;
}
} else {
return 0.05;
}
}
return 0;
}
// After
function getDiscount(user) {
if (!user) return 0;
if (!user.isPremium) return 0.05;
if (user.yearsActive > 5) return 0.3;
return 0.15;
}Step 3: Execute in Small Steps
For each refactoring step:
- Make the change (one pattern at a time).
- Run tests to verify behavior is unchanged.
- Review the diff to confirm it is purely structural.
- Commit the change with a descriptive message.
If tests fail after a refactoring step, revert and investigate before proceeding.
Step 4: Verify and Clean Up
After all refactoring steps are complete:
- Run the full test suite.
- Check for unused imports, dead code, or orphaned files created during refactoring.
- Verify that public APIs (function signatures, exports, endpoints) have not changed unless intended.
- Review the final diff as a whole to ensure the refactoring achieved its goals.
Output Format
## Refactoring Plan
### Current State
**File**: <path>
**Issues identified**:
- <code smell 1 with location>
- <code smell 2 with location>
**Test coverage**: <percentage or description>
### Refactoring Steps
#### Step 1: <refactoring pattern name>
**Target**: <function/class/block>
**Rationale**: <why this improves the code>
**Before**:
```<language>
<current code>After:
<refactored code>Verification: Run <test command>
Step 2: <next pattern>
...
Summary
- Lines of code:
<before>-><after> - Cyclomatic complexity:
<before>-><after> - Functions extracted:
<count> - Test coverage:
<before>-><after>
Risks and Mitigations
- <risk 1>:
<mitigation>
## Examples
**User**: "This function is 200 lines long, help me break it up"
**Action**: Read the function, identify logical sections, extract each section into a named function with clear parameters and return values, verify with tests at each step.
**User**: "Refactor this class to use the strategy pattern"
**Action**: Identify the conditional logic that varies, define a strategy interface, implement concrete strategies, replace conditionals with strategy dispatch, verify behavior is unchanged.
**User**: "Simplify this deeply nested code"
**Action**: Apply guard clauses to flatten nesting, extract helper functions for complex conditions, replace nested callbacks with async/await if applicable.
**User**: "This module has a lot of duplicated code"
**Action**: Identify duplicated blocks, extract shared logic into reusable functions, parameterize the differences, update all call sites, verify with tests.
## Best Practices
- Never refactor without tests. If tests do not exist, write them first. The tests are what guarantee behavior is preserved.
- Make one type of change at a time. Do not rename variables in the same commit as extracting methods. Keep each step verifiable.
- Refactoring should not change behavior. If you find a bug while refactoring, fix it in a separate commit so the fix is visible in the history.
- Commit after each successful refactoring step. Small commits make it easy to bisect if something goes wrong later.
- Name extracted functions based on WHAT they do (intent), not HOW they do it (implementation).
- Do not over-abstract. Extracting a function used only once may reduce readability rather than improve it. The rule of three is a good guideline: abstract when you see the same pattern three times.
- Preserve the public API unless the refactoring explicitly aims to change it. Internal restructuring should be invisible to callers.
- Use the IDE or editor's refactoring tools when available (rename symbol, extract method) as they handle all references automatically.
- Consider readability from the perspective of someone seeing the code for the first time. Clever code that is hard to follow defeats the purpose of refactoring.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.

