Best use case
Code Refactoring is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
## Refactoring Principles
Teams using Code Refactoring should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/code-refactoring/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How Code Refactoring Compares
| Feature / Agent | Code Refactoring | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
## Refactoring Principles
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
SKILL.md Source
# Code Refactoring
## Refactoring Principles
### When to Refactor
- Before adding new features (make change easy, then make easy change)
- After getting tests passing (red-green-refactor)
- When you see code smells
- During code review feedback
### When NOT to Refactor
- Without tests covering the code
- Under tight deadlines with no safety net
- Code that will be replaced soon
- When you don't understand what the code does
## Common Code Smells
### Long Methods
```typescript
// BEFORE: Method doing too much
function processOrder(order: Order) {
// 100 lines of validation, calculation, notification, logging...
}
// AFTER: Extract into focused methods
function processOrder(order: Order) {
validateOrder(order);
const total = calculateTotal(order);
saveOrder(order, total);
notifyCustomer(order);
}
```
### Deeply Nested Conditionals
```typescript
// BEFORE: Arrow code
function getDiscount(user: User, order: Order) {
if (user) {
if (user.isPremium) {
if (order.total > 100) {
if (order.items.length > 5) {
return 0.2;
}
}
}
}
return 0;
}
// AFTER: Early returns (guard clauses)
function getDiscount(user: User, order: Order) {
if (!user) return 0;
if (!user.isPremium) return 0;
if (order.total <= 100) return 0;
if (order.items.length <= 5) return 0;
return 0.2;
}
```
### Primitive Obsession
```typescript
// BEFORE: Primitives everywhere
function createUser(name: string, email: string, phone: string) {
if (!email.includes('@')) throw new Error('Invalid email');
// more validation...
}
// AFTER: Value objects
class Email {
constructor(private value: string) {
if (!value.includes('@')) throw new Error('Invalid email');
}
toString() { return this.value; }
}
function createUser(name: string, email: Email, phone: Phone) {
// Email is already validated
}
```
### Feature Envy
```typescript
// BEFORE: Method uses another object's data extensively
function calculateShipping(order: Order) {
const address = order.customer.address;
const weight = order.items.reduce((sum, i) => sum + i.weight, 0);
const distance = calculateDistance(address.zip);
return weight * distance * 0.01;
}
// AFTER: Move method to where the data is
class Order {
calculateShipping() {
return this.totalWeight * this.customer.shippingDistance * 0.01;
}
}
```
## Refactoring Techniques
### Extract Method
```typescript
// Identify a code block that does one thing
// Move it to a new method with a descriptive name
// Replace original code with method call
function printReport(data: ReportData) {
// Extract this block...
const header = `Report: ${data.title}\nDate: ${data.date}\n${'='.repeat(40)}`;
console.log(header);
// ...into a method
printHeader(data);
}
```
### Replace Conditional with Polymorphism
```typescript
// BEFORE: Switch on type
function getArea(shape: Shape) {
switch (shape.type) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return shape.base * shape.height / 2;
}
}
// AFTER: Polymorphic classes
interface Shape {
getArea(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
getArea() { return Math.PI * this.radius ** 2; }
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
getArea() { return this.width * this.height; }
}
```
### Introduce Parameter Object
```typescript
// BEFORE: Too many parameters
function searchProducts(
query: string,
minPrice: number,
maxPrice: number,
category: string,
inStock: boolean,
sortBy: string,
sortOrder: string
) { ... }
// AFTER: Parameter object
interface SearchParams {
query: string;
priceRange: { min: number; max: number };
category?: string;
inStock?: boolean;
sort?: { by: string; order: 'asc' | 'desc' };
}
function searchProducts(params: SearchParams) { ... }
```
### Replace Magic Numbers with Constants
```typescript
// BEFORE
if (user.age >= 18 && order.total >= 50) {
applyDiscount(order, 0.1);
}
// AFTER
const MINIMUM_AGE = 18;
const DISCOUNT_THRESHOLD = 50;
const STANDARD_DISCOUNT = 0.1;
if (user.age >= MINIMUM_AGE && order.total >= DISCOUNT_THRESHOLD) {
applyDiscount(order, STANDARD_DISCOUNT);
}
```
## Safe Refactoring Process
1. **Ensure tests exist** - Write tests if they don't
2. **Make small changes** - One refactoring at a time
3. **Run tests after each change** - Catch regressions immediately
4. **Commit frequently** - Easy to revert if something breaks
5. **Review the diff** - Make sure behavior hasn't changed
## Refactoring Checklist
- [ ] Tests pass before starting
- [ ] Each change is small and focused
- [ ] Tests pass after each change
- [ ] No behavior changes (only structure)
- [ ] Code is more readable than before
- [ ] Commit message explains the refactoringRelated Skills
java-refactoring-remove-parameter
Refactoring using Remove Parameter in Java Language
java-refactoring-extract-method
Refactoring using Extract Methods in Java Language
dry-refactoring
Guides systematic code refactoring following the DRY (Don't Repeat Yourself) principle. Use when user asks to eliminate code duplication, refactor repetitive code, apply DRY principle, or mentions code smells like copy-paste, magic numbers, or repeated logic. Implements a 4-step workflow from identifying repetition to verified refactoring.
code-refactoring-tech-debt
You are a technical debt expert specializing in identifying, quantifying, and prioritizing technical debt in software projects. Analyze the codebase to uncover debt, assess its impact, and create acti
code-refactoring-refactor-clean
You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance.
code-refactoring-context-restore
Use when working with code refactoring context restore
component-refactoring
Refactor high-complexity React components in Dify frontend. Use when `pnpm analyze-component --json` shows complexity > 50 or lineCount > 300, when the user asks for code splitting, hook extraction, or complexity reduction, or when `pnpm analyze-component` warns to refactor before testing; avoid for simple/well-structured components, third-party wrappers, or when the user explicitly wants testing without refactoring.
refactoring
Systematic refactoring with small-step discipline. Use when user says 'refactor', 'clean up', 'restructure', 'extract', 'rename', 'simplify', or mentions code smells. Enforces one change → test → commit cycle. For structural improvements, NOT style/formatting (use /lint). NOT for adding features or fixing bugs.
optimizing-cache-performance
Execute this skill enables AI assistant to analyze and improve application caching strategies. it optimizes cache hit rates, ttl configurations, cache key design, and invalidation strategies. use this skill when the user requests to "optimize cache performance"... Use when optimizing performance. Trigger with phrases like 'optimize', 'performance', or 'speed up'.
openapi-spec-generator
Openapi Spec Generator - Auto-activating skill for API Development. Triggers on: openapi spec generator, openapi spec generator Part of the API Development skill category.
open-graph-creator
Open Graph Creator - Auto-activating skill for Frontend Development. Triggers on: open graph creator, open graph creator Part of the Frontend Development skill category.
onnx-converter
Onnx Converter - Auto-activating skill for ML Deployment. Triggers on: onnx converter, onnx converter Part of the ML Deployment skill category.