AgentSkillsCN

refactoring

在不改变行为的情况下改善代码结构。当清理代码、降低复杂度,或被要求重构时使用。

SKILL.md
--- frontmatter
name: 'refactoring'
description: 'Improves code structure without changing behavior. Use when cleaning up code, reducing complexity, or when asked to refactor.'
<!-- PromptScript 2026-01-27T13:03:51.814Z - do not edit -->

Refactoring

Golden Rule

Change behavior OR change structure, never both at once.

Workflow

  1. Ensure tests exist - Coverage before refactoring
  2. Make small changes - One refactoring at a time
  3. Run tests frequently - After each change
  4. Commit often - Easy to revert if needed

Common Refactorings

Extract Function

Before:

typescript
function processOrder(order: Order) {
  // 20 lines of validation
  // 30 lines of calculation
  // 15 lines of formatting
}

After:

typescript
function processOrder(order: Order) {
  validateOrder(order);
  const total = calculateTotal(order);
  return formatReceipt(order, total);
}

Replace Conditionals with Polymorphism

Before:

typescript
function getPrice(type: string) {
  if (type === 'regular') return basePrice;
  if (type === 'premium') return basePrice * 1.5;
  if (type === 'vip') return basePrice * 2;
}

After:

typescript
interface PricingStrategy {
  getPrice(basePrice: number): number;
}

const strategies: Record<string, PricingStrategy> = {
  regular: { getPrice: (p) => p },
  premium: { getPrice: (p) => p * 1.5 },
  vip: { getPrice: (p) => p * 2 },
};

Simplify Conditionals

Before:

typescript
if (user && user.isActive && user.subscription && user.subscription.isValid) {

After:

typescript
function hasValidSubscription(user: User): boolean {
  return user?.isActive && user?.subscription?.isValid;
}

if (hasValidSubscription(user)) {

Code Smells to Address

SmellRefactoring
Long functionExtract function
Duplicate codeExtract and reuse
Long parameter listIntroduce parameter object
Feature envyMove method to appropriate class
Primitive obsessionReplace with value object
Switch statementsReplace with polymorphism

When NOT to Refactor

  • No test coverage (add tests first)
  • Under time pressure (technical debt is ok short-term)
  • Code is about to be replaced
  • Refactoring scope is unclear