code-refactoring-patterns

Systematic approach to refactoring code for improved maintainability, performance, and clarity while preserving functionality

Best use case

code-refactoring-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Systematic approach to refactoring code for improved maintainability, performance, and clarity while preserving functionality

Teams using code-refactoring-patterns 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

$curl -o ~/.claude/skills/code-refactoring-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/organvm-iv-taxis/a-i--skills/main/distributions/claude/skills/code-refactoring-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/code-refactoring-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How code-refactoring-patterns Compares

Feature / Agentcode-refactoring-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Systematic approach to refactoring code for improved maintainability, performance, and clarity while preserving functionality

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

SKILL.md Source

# Code Refactoring Patterns

A comprehensive guide to refactoring code systematically while maintaining functionality and improving quality.

## When to Refactor

- Code smells detected (duplicated code, long functions, etc.)
- Before adding new features to complex areas
- After understanding improves ("now I see a better way")
- When tests are in place
- Performance optimization needed

## Refactoring Rules

1. **Never refactor without tests**: Write tests first if they don't exist
2. **Small steps**: Make one change at a time
3. **Run tests after each change**: Ensure nothing breaks
4. **Commit often**: Each working refactor is a commit
5. **Don't mix refactoring with feature work**: Separate concerns

## Common Code Smells

### 1. Long Method/Function

**Smell**: Functions over 20-30 lines

**Refactor**: Extract Method

```typescript
// Before
function processOrder(order: Order) {
  // Validate order (10 lines)
  // Calculate totals (15 lines)
  // Apply discounts (12 lines)
  // Send confirmation (8 lines)
}

// After
function processOrder(order: Order) {
  validateOrder(order);
  const totals = calculateTotals(order);
  const finalPrice = applyDiscounts(totals, order);
  sendConfirmation(order, finalPrice);
}
```

### 2. Duplicated Code

**Smell**: Same code in multiple places

**Refactor**: Extract Function/Class

```typescript
// Before
function formatUserName(user: User) {
  return `${user.firstName} ${user.lastName}`;
}

function formatAuthorName(author: Author) {
  return `${author.firstName} ${author.lastName}`;
}

// After
function formatFullName(person: { firstName: string; lastName: string }) {
  return `${person.firstName} ${person.lastName}`;
}
```

### 3. Long Parameter List

**Smell**: Functions with 4+ parameters

**Refactor**: Parameter Object

```typescript
// Before
function createUser(
  firstName: string,
  lastName: string,
  email: string,
  phone: string,
  address: string
) { }

// After
interface UserDetails {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address: string;
}

function createUser(details: UserDetails) { }
```

### 4. Large Class

**Smell**: Classes with many responsibilities

**Refactor**: Extract Class

```typescript
// Before
class UserManager {
  createUser() { }
  deleteUser() { }
  sendEmail() { }
  generateReport() { }
  logActivity() { }
}

// After
class UserService {
  createUser() { }
  deleteUser() { }
}

class EmailService {
  sendEmail() { }
}

class ReportService {
  generateReport() { }
}
```

### 5. Feature Envy

**Smell**: Method uses data from another class more than its own

**Refactor**: Move Method

```typescript
// Before
class Order {
  calculate() {
    return this.customer.getDiscount() * this.amount;
  }
}

// After
class Customer {
  calculateOrderAmount(order: Order) {
    return this.getDiscount() * order.amount;
  }
}
```

## Refactoring Techniques

### Extract Method

Break large functions into smaller, named pieces:

```typescript
// Before
function renderUser(user: User) {
  console.log(`<div>`);
  console.log(`  <h1>${user.firstName} ${user.lastName}</h1>`);
  console.log(`  <p>${user.email}</p>`);
  console.log(`</div>`);
}

// After
function renderUser(user: User) {
  console.log(`<div>`);
  console.log(`  ${renderUserHeader(user)}`);
  console.log(`  ${renderUserEmail(user)}`);
  console.log(`</div>`);
}

function renderUserHeader(user: User) {
  return `<h1>${user.firstName} ${user.lastName}</h1>`;
}

function renderUserEmail(user: User) {
  return `<p>${user.email}</p>`;
}
```

### Rename for Clarity

Use descriptive names:

```typescript
// Before
function calc(a: number, b: number) {
  return a * b * 0.08;
}

// After
function calculateSalesTax(amount: number, quantity: number) {
  const TAX_RATE = 0.08;
  return amount * quantity * TAX_RATE;
}
```

### Introduce Explaining Variable

Make complex expressions clear:

```typescript
// Before
if (platform.toUpperCase().includes('MAC') && 
    browser.toUpperCase().includes('IE') &&
    wasInitialized() && resized) {
  // do something
}

// After
const isMacOS = platform.toUpperCase().includes('MAC');
const isIE = browser.toUpperCase().includes('IE');
const wasResized = wasInitialized() && resized;

if (isMacOS && isIE && wasResized) {
  // do something
}
```

### Replace Conditional with Polymorphism

Use inheritance/interfaces instead of switch/if-else chains:

```typescript
// Before
function getSpeed(vehicle: Vehicle) {
  switch (vehicle.type) {
    case 'car': return vehicle.speed * 1.0;
    case 'bike': return vehicle.speed * 0.8;
    case 'truck': return vehicle.speed * 0.6;
  }
}

// After
interface Vehicle {
  getSpeed(): number;
}

class Car implements Vehicle {
  getSpeed() { return this.speed * 1.0; }
}

class Bike implements Vehicle {
  getSpeed() { return this.speed * 0.8; }
}
```

### Simplify Conditional Logic

Use early returns and guard clauses:

```typescript
// Before
function processPayment(payment: Payment) {
  if (payment.isValid()) {
    if (payment.amount > 0) {
      if (payment.method === 'card') {
        // process card payment
      } else {
        // invalid method
      }
    } else {
      // invalid amount
    }
  } else {
    // invalid payment
  }
}

// After
function processPayment(payment: Payment) {
  if (!payment.isValid()) {
    throw new Error('Invalid payment');
  }
  
  if (payment.amount <= 0) {
    throw new Error('Invalid amount');
  }
  
  if (payment.method !== 'card') {
    throw new Error('Invalid method');
  }
  
  // process card payment
}
```

## Refactoring Workflow

### Step 1: Understand Current Code

```bash
# Read the code thoroughly
cat src/feature.ts

# Check tests
cat src/feature.test.ts

# Find all usages
grep -r "functionName" src/
```

### Step 2: Ensure Tests Exist

```bash
# Run existing tests
npm test src/feature.test.ts

# Add missing tests if needed
```

### Step 3: Refactor in Small Steps

```bash
# Make one refactoring change
# Run tests
npm test

# Commit if tests pass
git add . && git commit -m "refactor: extract method calculateTotal"

# Repeat for next refactoring
```

### Step 4: Verify No Regression

```bash
# Run full test suite
npm test

# Check type errors
npx tsc --noEmit

# Verify lint
npm run lint
```

### Step 5: Performance Check

```bash
# Compare before/after if performance-critical
npm run benchmark
```

## Refactoring Checklist

Before refactoring:
- [ ] Tests exist and pass
- [ ] Understand current behavior
- [ ] Know why refactoring is needed
- [ ] Have time to complete refactoring

During refactoring:
- [ ] Make one change at a time
- [ ] Run tests after each change
- [ ] Keep commits small and focused
- [ ] Don't add features during refactoring

After refactoring:
- [ ] All tests pass
- [ ] No type errors
- [ ] Lint passes
- [ ] Code review completed
- [ ] Documentation updated if needed

## Integration Points

Complements:
- **verification-loop**: For validation after refactoring
- **tdd-workflow**: For test-first approach
- **coding-standards-enforcer**: For style consistency
- **testing-patterns**: For test design

## Refactoring Anti-Patterns

❌ **Don't**:
- Refactor without tests
- Mix refactoring with feature work
- Make large changes at once
- Refactor code you don't understand
- Skip verification steps

✅ **Do**:
- Write tests first
- Separate refactoring commits
- Make incremental changes
- Understand code before refactoring
- Run tests frequently

Related Skills

webhook-integration-patterns

5
from organvm-iv-taxis/a-i--skills

Designs reliable webhook systems with proper delivery guarantees, retry logic, signature verification, and idempotent processing for event-driven integrations.

vector-search-patterns

5
from organvm-iv-taxis/a-i--skills

Implement vector similarity search with embedding generation, index selection, and hybrid retrieval strategies. Covers ChromaDB, pgvector, FAISS, and RAG pipeline design. Triggers on vector search, embeddings, semantic search, or RAG architecture requests.

testing-patterns

5
from organvm-iv-taxis/a-i--skills

Write effective tests across the stack—unit, integration, E2E, and visual regression. Covers testing philosophy, framework selection, mocking strategies, and CI integration. Triggers on testing, test coverage, TDD, or quality assurance requests.

session-lifecycle-patterns

5
from organvm-iv-taxis/a-i--skills

Manage AI agent session lifecycles with structured phases (FRAME, SHAPE, BUILD, PROVE), context preservation across sessions, handoff protocols, and session metadata tracking. Triggers on session management, agent lifecycle, or multi-session workflow requests.

responsive-design-patterns

5
from organvm-iv-taxis/a-i--skills

Mobile-first responsive design patterns with breakpoints, fluid layouts, and adaptive components

resilience-patterns

5
from organvm-iv-taxis/a-i--skills

Build fault-tolerant systems with circuit breakers, retries with backoff, bulkheads, timeouts, and graceful degradation. Covers distributed system failure modes and recovery strategies. Triggers on reliability engineering, fault tolerance, or distributed system resilience requests.

redis-patterns

5
from organvm-iv-taxis/a-i--skills

Use Redis effectively for caching, pub/sub messaging, rate limiting, distributed locks, and session storage. Covers data structure selection, expiration strategies, and cluster patterns. Triggers on Redis usage, caching architecture, or pub/sub messaging requests.

realtime-websocket-patterns

5
from organvm-iv-taxis/a-i--skills

Implement real-time features with WebSockets, Server-Sent Events, and long polling. Covers connection management, room-based messaging, presence tracking, and scaling strategies. Triggers on WebSocket implementation, real-time communication, or live update feature requests.

react-three-fiber-patterns

5
from organvm-iv-taxis/a-i--skills

Build interactive 3D experiences in React using react-three-fiber (R3F), drei helpers, and shader integration. Covers scene composition, performance optimization, and animation patterns. Triggers on R3F development, React + Three.js, or declarative 3D scene requests.

python-packaging-patterns

5
from organvm-iv-taxis/a-i--skills

Structure Python projects for distribution with pyproject.toml, src layouts, dependency management, and publishing workflows. Covers packaging tools (hatch, setuptools, flit, poetry), versioning strategies, and editable installs. Triggers on Python project setup, packaging configuration, or dependency management requests.

prompt-engineering-patterns

5
from organvm-iv-taxis/a-i--skills

Design effective prompts for LLM agents with structured input/output formats, chain-of-thought reasoning, few-shot examples, and system prompt architecture. Covers Claude-specific patterns and multi-turn conversation design. Triggers on prompt design, LLM interaction patterns, or system prompt architecture requests.

postgres-advanced-patterns

5
from organvm-iv-taxis/a-i--skills

Advanced PostgreSQL patterns for performance optimization, complex queries, indexing strategies, and database design