home / skills / aidotnet / moyucode / refactor-assistant

refactor-assistant skill

/skills/community/refactor-assistant

This skill helps you improve TypeScript code quality by applying refactoring techniques, design patterns, and safe transformations that preserve behavior.

npx playbooks add skill aidotnet/moyucode --skill refactor-assistant

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.3 KB
---
name: refactor-assistant
description: 智能代码重构,提供设计模式建议、代码异味检测和保持行为不变的安全转换策略。
metadata:
  short-description: 使用设计模式重构代码
---

# Refactor Assistant Skill

## Description
Improve code quality through systematic refactoring with design pattern recommendations.

## Trigger
- `/refactor` command
- User requests code improvement
- User asks about design patterns

## Prompt

You are a refactoring expert that improves code quality while preserving behavior.

### Extract Method

```typescript
// ❌ Before: Long method with multiple responsibilities
function processOrder(order: Order) {
  // Validate order
  if (!order.items.length) throw new Error('Empty order');
  if (!order.customer) throw new Error('No customer');
  
  // Calculate total
  let total = 0;
  for (const item of order.items) {
    total += item.price * item.quantity;
    if (item.discount) {
      total -= item.discount;
    }
  }
  
  // Apply tax
  const tax = total * 0.1;
  total += tax;
  
  // Save and notify
  db.save(order);
  emailService.send(order.customer.email, `Order total: ${total}`);
}

// ✅ After: Small, focused methods
function processOrder(order: Order) {
  validateOrder(order);
  const total = calculateTotal(order);
  saveAndNotify(order, total);
}

function validateOrder(order: Order): void {
  if (!order.items.length) throw new Error('Empty order');
  if (!order.customer) throw new Error('No customer');
}

function calculateTotal(order: Order): number {
  const subtotal = order.items.reduce((sum, item) => {
    const itemTotal = item.price * item.quantity - (item.discount ?? 0);
    return sum + itemTotal;
  }, 0);
  return subtotal * 1.1; // Include 10% tax
}
```

### Strategy Pattern

```typescript
// ❌ Before: Switch statement for different behaviors
function calculateShipping(order: Order): number {
  switch (order.shippingMethod) {
    case 'standard': return order.weight * 0.5;
    case 'express': return order.weight * 1.5 + 10;
    case 'overnight': return order.weight * 3 + 25;
    default: throw new Error('Unknown method');
  }
}

// ✅ After: Strategy pattern
interface ShippingStrategy {
  calculate(order: Order): number;
}

class StandardShipping implements ShippingStrategy {
  calculate(order: Order): number {
    return order.weight * 0.5;
  }
}

class ExpressShipping implements ShippingStrategy {
  calculate(order: Order): number {
    return order.weight * 1.5 + 10;
  }
}

class ShippingCalculator {
  constructor(private strategy: ShippingStrategy) {}
  
  calculate(order: Order): number {
    return this.strategy.calculate(order);
  }
}
```

### Factory Pattern

```typescript
// ✅ Factory for creating different notification types
interface Notification {
  send(message: string): Promise<void>;
}

class NotificationFactory {
  static create(type: 'email' | 'sms' | 'push'): Notification {
    switch (type) {
      case 'email': return new EmailNotification();
      case 'sms': return new SmsNotification();
      case 'push': return new PushNotification();
    }
  }
}

// Usage
const notification = NotificationFactory.create('email');
await notification.send('Hello!');
```

## Tags
`refactoring`, `design-patterns`, `code-quality`, `clean-code`, `architecture`

## Compatibility
- Codex: ✅
- Claude Code: ✅

Overview

This skill provides an intelligent refactor assistant that suggests safe, behavior-preserving code transformations and design pattern improvements. It detects common code smells, recommends targeted refactorings (like Extract Method), and suggests pattern-based restructures (Strategy, Factory) for clearer architecture. The focus is on maintainability, readability, and minimal-risk changes.

How this skill works

The assistant analyzes TypeScript code to identify long methods, duplicated logic, large switch statements, and other smells. It proposes concrete refactor steps, small focused helper methods, and pattern conversions with example implementations. Each suggestion emphasizes preserving existing behavior and minimizing breaking changes, and includes rationale and migration guidance.

When to use it

  • You have long methods with multiple responsibilities and want to split them safely.
  • You have large switch/case blocks or conditionals that map well to Strategy or State patterns.
  • You need a factory or builder to centralize construction of related objects.
  • You want to remove duplication and improve testability without changing runtime behavior.
  • You’re preparing code for incremental architecture improvements or easier feature addition.

Best practices

  • Start with small, focused refactors (Extract Method, Rename) and validate with tests before large restructures.
  • Keep behavior preservation as the priority: run unit/integration tests after each change and use feature flags for risky flows.
  • Prefer composition and single responsibility: each function or class should do one thing well.
  • When applying patterns, provide clear interfaces and a simple migration path from the old code (adapters or thin facades).
  • Document the intent of refactors in commit messages and link to failing examples or code smells that motivated the change.

Example use cases

  • Extract Method to split a 200-line function into validation, calculation, and persistence helpers with unit tests.
  • Replace a multi-branch shipping cost switch with Strategy classes to add new methods without modifying existing code.
  • Introduce a NotificationFactory to centralize creation of email, SMS, and push notifications and simplify client code.
  • Detect duplicated subtotal/tax calculations and consolidate them into a single calculateTotal function used by multiple services.
  • Suggest a safe sequence to migrate a monolithic service into smaller collaborators while preserving API behavior.