refactor-legacy-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactor Legacy Code

重构遗留代码

Overview

概述

This skill helps you systematically refactor legacy code to improve maintainability, readability, and performance while preserving existing functionality. It follows industry best practices for safe refactoring with comprehensive testing.
该技能可帮助你系统性地重构遗留代码,在保留现有功能的同时提高可维护性、可读性和性能。它遵循行业最佳实践,通过全面测试实现安全重构。

When to Use

适用场景

  • Modernizing outdated code patterns or deprecated APIs
  • Reducing technical debt in existing codebases
  • Improving code readability and maintainability
  • Extracting reusable components from monolithic code
  • Upgrading to newer language features or frameworks
  • Preparing code for new feature development
  • 现代化过时的代码模式或已弃用的API
  • 减少现有代码库中的技术债务
  • 提高代码的可读性和可维护性
  • 从单体代码中提取可复用组件
  • 升级到更新的语言特性或框架
  • 为新功能开发准备代码

Instructions

操作指南

1. Code Assessment

1. 代码评估

First, analyze the legacy code to understand:
bash
undefined
首先,分析遗留代码以了解:
bash
undefined

Review the codebase structure

查看代码库结构

tree -L 3 -I 'node_modules|dist|build'
tree -L 3 -I 'node_modules|dist|build'

Check for outdated dependencies

检查过时的依赖

npm outdated # or pip list --outdated, composer outdated, etc.
npm outdated # 或 pip list --outdated、composer outdated等

Identify code complexity hotspots

识别代码复杂度热点

Use tools like:

使用以下工具:

- SonarQube for code smells

- SonarQube 检测代码异味

- eslint for JavaScript

- eslint 用于JavaScript

- pylint for Python

- pylint 用于Python

- RuboCop for Ruby

- RuboCop 用于Ruby


**Assessment Checklist:**
- [ ] Identify deprecated patterns and APIs
- [ ] Locate tightly coupled components
- [ ] Find duplicated code blocks
- [ ] Review test coverage gaps
- [ ] Document current behavior and edge cases
- [ ] Identify performance bottlenecks

**评估检查清单:**
- [ ] 识别已弃用的模式和API
- [ ] 定位紧耦合的组件
- [ ] 查找重复的代码块
- [ ] 检查测试覆盖率缺口
- [ ] 记录当前行为和边缘情况
- [ ] 识别性能瓶颈

2. Establish Safety Net

2. 建立安全保障

Before refactoring, ensure you have comprehensive tests:
javascript
// Add characterization tests to lock in current behavior
describe('LegacyFeature', () => {
  it('should preserve existing behavior during refactoring', () => {
    // Test current implementation behavior
    const input = { /* realistic test data */ };
    const result = legacyFunction(input);

    // Document expected output
    expect(result).toEqual({ /* current actual output */ });
  });
});
Testing Strategy:
  • Add unit tests for critical paths
  • Create integration tests for component interactions
  • Document edge cases and error scenarios
  • Set up test coverage monitoring
  • Run tests before each refactoring step
在重构前,确保你拥有全面的测试:
javascript
// 添加特征测试以锁定当前行为
describe('LegacyFeature', () => {
  it('should preserve existing behavior during refactoring', () => {
    // 测试当前实现的行为
    const input = { /* 真实测试数据 */ };
    const result = legacyFunction(input);

    // 记录预期输出
    expect(result).toEqual({ /* 当前实际输出 */ });
  });
});
测试策略:
  • 为关键路径添加单元测试
  • 创建组件交互的集成测试
  • 记录边缘情况和错误场景
  • 设置测试覆盖率监控
  • 在每个重构步骤前运行测试

3. Incremental Refactoring

3. 增量式重构

Apply refactoring patterns systematically:
系统性地应用重构模式:

Extract Function/Method

提取函数/方法

javascript
// BEFORE: Long, complex function
function processUserData(user) {
  // 50 lines of mixed validation, transformation, and business logic
  if (!user.email || !user.email.includes('@')) return null;
  const normalized = user.email.toLowerCase().trim();
  // ... more complex logic
}

// AFTER: Extracted, focused functions
function validateEmail(email) {
  return email && email.includes('@');
}

function normalizeEmail(email) {
  return email.toLowerCase().trim();
}

function processUserData(user) {
  if (!validateEmail(user.email)) return null;
  const email = normalizeEmail(user.email);
  // Clear, readable flow
}
javascript
// 重构前:冗长复杂的函数
function processUserData(user) {
  // 50行混合了验证、转换和业务逻辑的代码
  if (!user.email || !user.email.includes('@')) return null;
  const normalized = user.email.toLowerCase().trim();
  // ... 更多复杂逻辑
}

// 重构后:提取后的专注函数
function validateEmail(email) {
  return email && email.includes('@');
}

function normalizeEmail(email) {
  return email.toLowerCase().trim();
}

function processUserData(user) {
  if (!validateEmail(user.email)) return null;
  const email = normalizeEmail(user.email);
  // 清晰可读的流程
}

Replace Conditionals with Polymorphism

用多态替代条件语句

python
undefined
python
undefined

BEFORE: Complex conditional logic

重构前:复杂的条件逻辑

def calculate_price(customer_type, base_price): if customer_type == 'regular': return base_price elif customer_type == 'premium': return base_price * 0.9 elif customer_type == 'vip': return base_price * 0.8 else: return base_price
def calculate_price(customer_type, base_price): if customer_type == 'regular': return base_price elif customer_type == 'premium': return base_price * 0.9 elif customer_type == 'vip': return base_price * 0.8 else: return base_price

AFTER: Polymorphic approach

重构后:多态实现

class PricingStrategy: def calculate(self, base_price): return base_price
class RegularPricing(PricingStrategy): pass
class PremiumPricing(PricingStrategy): def calculate(self, base_price): return base_price * 0.9
class VIPPricing(PricingStrategy): def calculate(self, base_price): return base_price * 0.8
class PricingStrategy: def calculate(self, base_price): return base_price
class RegularPricing(PricingStrategy): pass
class PremiumPricing(PricingStrategy): def calculate(self, base_price): return base_price * 0.9
class VIPPricing(PricingStrategy): def calculate(self, base_price): return base_price * 0.8
// 使用方式 pricing = pricing_strategies[customer_type] price = pricing.calculate(base_price)
undefined

Usage

引入参数对象

pricing = pricing_strategies[customer_type] price = pricing.calculate(base_price)
undefined
typescript
// 重构前:冗长的参数列表
function createUser(
  firstName: string,
  lastName: string,
  email: string,
  phone: string,
  address: string,
  city: string,
  state: string,
  zip: string
) {
  // ...
}

// 重构后:参数对象
interface UserData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address: Address;
}

interface Address {
  street: string;
  city: string;
  state: string;
  zip: string;
}

function createUser(userData: UserData) {
  // ...
}

Introduce Parameter Object

4. 现代化模式

typescript
// BEFORE: Long parameter lists
function createUser(
  firstName: string,
  lastName: string,
  email: string,
  phone: string,
  address: string,
  city: string,
  state: string,
  zip: string
) {
  // ...
}

// AFTER: Parameter object
interface UserData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address: Address;
}

interface Address {
  street: string;
  city: string;
  state: string;
  zip: string;
}

function createUser(userData: UserData) {
  // ...
}
用现代等价模式替代过时模式:

4. Modernize Patterns

用Promise替代回调

Replace outdated patterns with modern equivalents:
javascript
// 重构前:回调地狱
function fetchUserData(userId, callback) {
  db.query('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
    if (err) return callback(err);
    db.query('SELECT * FROM orders WHERE user_id = ?', [userId], (err, orders) => {
      if (err) return callback(err);
      callback(null, { user, orders });
    });
  });
}

// 重构后:Async/await
async function fetchUserData(userId) {
  const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
  const orders = await db.query('SELECT * FROM orders WHERE user_id = ?', [userId]);
  return { user, orders };
}

Promises over Callbacks

现代语言特性

javascript
// BEFORE: Callback hell
function fetchUserData(userId, callback) {
  db.query('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
    if (err) return callback(err);
    db.query('SELECT * FROM orders WHERE user_id = ?', [userId], (err, orders) => {
      if (err) return callback(err);
      callback(null, { user, orders });
    });
  });
}

// AFTER: Async/await
async function fetchUserData(userId) {
  const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
  const orders = await db.query('SELECT * FROM orders WHERE user_id = ?', [userId]);
  return { user, orders };
}
javascript
// 重构前:var和字符串拼接
var userName = user.firstName + ' ' + user.lastName;
var isActive = user.status === 'active' ? true : false;

// 重构后:const/let和模板字符串
const userName = `${user.firstName} ${user.lastName}`;
const isActive = user.status === 'active';

Modern Language Features

5. 减少依赖

javascript
// BEFORE: var and string concatenation
var userName = user.firstName + ' ' + user.lastName;
var isActive = user.status === 'active' ? true : false;

// AFTER: const/let and template literals
const userName = `${user.firstName} ${user.lastName}`;
const isActive = user.status === 'active';
打破紧耦合:
python
undefined

5. Reduce Dependencies

重构前:与特定实现紧耦合

Break tight coupling:
python
undefined
class OrderProcessor: def init(self): self.db = MySQLDatabase() # 紧耦合 self.email = SendGridEmail() # 紧耦合
def process_order(self, order):
    self.db.save(order)
    self.email.send(order.customer_email, "Order confirmed")

BEFORE: Tight coupling to specific implementation

重构后:依赖注入

class OrderProcessor: def init(self): self.db = MySQLDatabase() # Tightly coupled self.email = SendGridEmail() # Tightly coupled
def process_order(self, order):
    self.db.save(order)
    self.email.send(order.customer_email, "Order confirmed")
class OrderProcessor: def init(self, database, email_service): self.db = database # 任何数据库实现 self.email = email_service # 任何邮件服务
def process_order(self, order):
    self.db.save(order)
    self.email.send(order.customer_email, "Order confirmed")
// 易于使用模拟对象测试 processor = OrderProcessor(MockDatabase(), MockEmailService())
undefined

AFTER: Dependency injection

6. 文档记录

class OrderProcessor: def init(self, database, email_service): self.db = database # Any database implementation self.email = email_service # Any email service
def process_order(self, order):
    self.db.save(order)
    self.email.send(order.customer_email, "Order confirmed")
记录重构决策:
markdown
undefined

Easy to test with mocks

重构日志

2025-01-15: 提取支付处理逻辑

processor = OrderProcessor(MockDatabase(), MockEmailService())
undefined
理由:支付逻辑嵌入在订单控制器中(500行) 变更
  • 提取了单一职责的PaymentService
  • 引入了PaymentGateway接口以提高灵活性
  • 添加了全面的单元测试(95%覆盖率) 破坏性变更:无(仅内部重构) 性能影响:订单处理时间提升15%

6. Documentation

2025-01-16: 用Async/Await替代回调

Document refactoring decisions:
markdown
undefined
理由:用户认证流程中的回调地狱 变更
  • 将所有认证方法转换为async/await
  • 用try/catch简化错误处理
  • 可读性提升(代码从150行减少到80行) 破坏性变更:函数签名变更(需要更新调用代码) 迁移:更新了控制器中的12处调用点
undefined

Refactoring Log

最佳实践

2025-01-15: Extract Payment Processing

✅ 建议

Rationale: Payment logic was embedded in order controller (500 lines) Changes:
  • Extracted PaymentService with single responsibility
  • Introduced PaymentGateway interface for flexibility
  • Added comprehensive unit tests (95% coverage) Breaking Changes: None (internal refactoring only) Performance Impact: 15% improvement in order processing time
  • 增量式重构:小的、可测试的变更
  • 频繁运行测试:每个重构步骤后都要运行
  • 经常提交:创建逻辑清晰的原子提交
  • 保持现有测试通过:不要破坏功能
  • 使用IDE重构工具:比手动编辑更安全
  • 检查代码覆盖率:确保测试覆盖重构后的代码
  • 记录决策:记录原因,而不只是内容
  • 寻求同行评审:新鲜视角能发现问题

2025-01-16: Replace Callback with Async/Await

❌ 避免

Rationale: Callback hell in user authentication flow Changes:
  • Converted all authentication methods to async/await
  • Simplified error handling with try/catch
  • Improved readability (reduced from 150 to 80 lines) Breaking Changes: Function signatures changed (requires updates in calling code) Migration: Updated all 12 call sites in controllers
undefined
  • 混合重构与新功能:分离关注点
  • 无测试重构:这是导致破坏性变更的根源
  • 改变行为:重构应保留功能
  • 大规模重构:增加风险和评审难度
  • 忽略代码异味:系统性地解决它们
  • 跳过文档:未来的维护者需要上下文

Best Practices

常见陷阱

✅ DO

1. 过度设计

  • Refactor incrementally: Small, testable changes
  • Run tests frequently: After each refactoring step
  • Commit often: Create logical, atomic commits
  • Keep existing tests passing: Don't break functionality
  • Use IDE refactoring tools: Safer than manual edits
  • Review code coverage: Ensure tests cover refactored code
  • Document decisions: Why, not just what
  • Seek peer review: Fresh eyes catch issues
javascript
// ❌ 简单场景下过于复杂
class UserNameFormatterFactory {
  createFormatter(type) {
    return new UserNameFormatter(new FormattingStrategy(type));
  }
}

// ✅ 简单场景下的合适实现
function formatUserName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}

❌ DON'T

2. 过早优化

  • Mix refactoring with new features: Separate concerns
  • Refactor without tests: Recipe for breaking changes
  • Change behavior: Refactoring should preserve functionality
  • Refactor large chunks: Increases risk and review difficulty
  • Ignore code smells: Address them systematically
  • Skip documentation: Future maintainers need context
先关注可读性,然后针对性能分析识别出的瓶颈进行优化。

Common Pitfalls

3. 破坏向后兼容性

1. Over-Engineering

javascript
// ❌ Too complex for simple case
class UserNameFormatterFactory {
  createFormatter(type) {
    return new UserNameFormatter(new FormattingStrategy(type));
  }
}

// ✅ Appropriate for simple case
function formatUserName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}
在移除公共API前使用弃用警告:
typescript
/** @deprecated Use createUser(userData) instead. Will be removed in v2.0 */
function createUserOld(firstName: string, lastName: string, email: string) {
  console.warn('createUserOld is deprecated. Use createUser(userData)');
  return createUser({ firstName, lastName, email });
}

2. Premature Optimization

测试策略

单元测试

Focus on readability first, then optimize bottlenecks identified by profiling.
javascript
describe('Refactored User Service', () => {
  describe('validateEmail', () => {
    it('should accept valid email formats', () => {
      expect(validateEmail('user@example.com')).toBe(true);
    });

    it('should reject invalid email formats', () => {
      expect(validateEmail('invalid')).toBe(false);
      expect(validateEmail('')).toBe(false);
      expect(validateEmail(null)).toBe(false);
    });
  });
});

3. Breaking Backward Compatibility

集成测试

Use deprecation warnings before removing public APIs:
typescript
/** @deprecated Use createUser(userData) instead. Will be removed in v2.0 */
function createUserOld(firstName: string, lastName: string, email: string) {
  console.warn('createUserOld is deprecated. Use createUser(userData)');
  return createUser({ firstName, lastName, email });
}
python
def test_refactored_order_processing():
    """Ensure refactored code maintains end-to-end behavior"""
    # 准备
    order = create_test_order()
    processor = OrderProcessor(test_database, test_email_service)

    # 执行
    result = processor.process_order(order)

    # 断言
    assert result.status == 'completed'
    assert test_database.orders.count() == 1
    assert test_email_service.sent_count == 1

Testing Strategy

回归测试

Unit Tests

javascript
describe('Refactored User Service', () => {
  describe('validateEmail', () => {
    it('should accept valid email formats', () => {
      expect(validateEmail('user@example.com')).toBe(true);
    });

    it('should reject invalid email formats', () => {
      expect(validateEmail('invalid')).toBe(false);
      expect(validateEmail('')).toBe(false);
      expect(validateEmail(null)).toBe(false);
    });
  });
});
运行完整测试套件以确保没有意外的副作用。

Integration Tests

重构模式参考

常见模式

python
def test_refactored_order_processing():
    """Ensure refactored code maintains end-to-end behavior"""
    # Arrange
    order = create_test_order()
    processor = OrderProcessor(test_database, test_email_service)

    # Act
    result = processor.process_order(order)

    # Assert
    assert result.status == 'completed'
    assert test_database.orders.count() == 1
    assert test_email_service.sent_count == 1
  1. 提取方法/函数:将长函数拆分为更小的函数
  2. 提取类:将相关功能分组
  3. 内联方法:移除不必要的间接层
  4. 移动方法:将方法放在合适的类中
  5. 重命名:使用描述性名称
  6. 替换魔术数字:使用命名常量
  7. 用多态替代条件语句:使用继承
  8. 引入参数对象:将相关参数分组
  9. 移除重复代码:遵循DRY原则
  10. 简化条件逻辑:降低复杂度

Regression Tests

工具与资源

静态分析工具

Run full test suite to ensure no unintended side effects.
  • JavaScript/TypeScript:ESLint、TSLint、SonarQube
  • Python:Pylint、Flake8、Bandit
  • Java:SonarQube、PMD、Checkstyle
  • Ruby:RuboCop、Reek
  • PHP:PHPStan、Psalm

Refactoring Patterns Reference

IDE重构支持

Common Patterns

  1. Extract Method/Function: Break long functions into smaller ones
  2. Extract Class: Group related functionality
  3. Inline Method: Remove unnecessary indirection
  4. Move Method: Place method in appropriate class
  5. Rename: Use descriptive names
  6. Replace Magic Numbers: Use named constants
  7. Replace Conditional with Polymorphism: Use inheritance
  8. Introduce Parameter Object: Group related parameters
  9. Remove Duplication: DRY principle
  10. Simplify Conditional Logic: Reduce complexity
  • VS Code:内置重构命令
  • JetBrains IDEs:全面的重构工具
  • Eclipse:自动化重构
  • Vim/Neovim:语言服务重构操作

Tools & Resources

推荐阅读

Static Analysis Tools

  • JavaScript/TypeScript: ESLint, TSLint, SonarQube
  • Python: Pylint, Flake8, Bandit
  • Java: SonarQube, PMD, Checkstyle
  • Ruby: RuboCop, Reek
  • PHP: PHPStan, Psalm
  • 《重构》(Martin Fowler 著)
  • 《修改代码的艺术》(Michael Feathers 著)
  • 《代码整洁之道》(Robert C. Martin 著)

IDE Refactoring Support

示例

完整重构示例

重构前

  • VS Code: Built-in refactoring commands
  • JetBrains IDEs: Comprehensive refactoring tools
  • Eclipse: Automated refactorings
  • Vim/Neovim: Language server refactoring actions
javascript
// legacy-user-service.js - 200行复杂、耦合的代码
var UserService = {
  createUser: function(fn, ln, em, ph, addr) {
    if (!em || em.indexOf('@') === -1) {
      return { error: 'Invalid email' };
    }
    var conn = mysql.createConnection(config);
    conn.connect();
    conn.query(
      'INSERT INTO users (first_name, last_name, email, phone, address) VALUES (?, ?, ?, ?, ?)',
      [fn, ln, em.toLowerCase(), ph, addr],
      function(err, result) {
        if (err) {
          console.log(err);
          return { error: 'Database error' };
        }
        // 发送欢迎邮件
        var nodemailer = require('nodemailer');
        var transporter = nodemailer.createTransport(emailConfig);
        transporter.sendMail({
          to: em,
          subject: 'Welcome!',
          html: '<h1>Welcome ' + fn + '!</h1>'
        }, function(err, info) {
          if (err) console.log(err);
        });
        conn.end();
        return { id: result.insertId };
      }
    );
  }
};

Recommended Reading

重构后

  • "Refactoring" by Martin Fowler
  • "Working Effectively with Legacy Code" by Michael Feathers
  • "Clean Code" by Robert C. Martin
typescript
// user-service.ts - 整洁、可测试、可维护
interface UserData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address: string;
}

class UserService {
  constructor(
    private database: Database,
    private emailService: EmailService,
    private validator: Validator
  ) {}

  async createUser(userData: UserData): Promise<User> {
    this.validator.validateEmail(userData.email);

    const normalizedData = this.normalizeUserData(userData);
    const user = await this.database.users.create(normalizedData);

    await this.sendWelcomeEmail(user);

    return user;
  }

  private normalizeUserData(data: UserData): UserData {
    return {
      ...data,
      email: data.email.toLowerCase().trim()
    };
  }

  private async sendWelcomeEmail(user: User): Promise<void> {
    await this.emailService.send({
      to: user.email,
      subject: 'Welcome!',
      template: 'welcome',
      data: { firstName: user.firstName }
    });
  }
}

// validator.ts
class Validator {
  validateEmail(email: string): void {
    if (!email || !email.includes('@')) {
      throw new ValidationError('Invalid email format');
    }
  }
}

// 易于测试
describe('UserService', () => {
  it('should create user with valid data', async () => {
    const mockDb = createMockDatabase();
    const mockEmail = createMockEmailService();
    const service = new UserService(mockDb, mockEmail, new Validator());

    const user = await service.createUser({
      firstName: 'John',
      lastName: 'Doe',
      email: 'john@example.com',
      phone: '555-0123',
      address: '123 Main St'
    });

    expect(user.id).toBeDefined();
    expect(mockDb.users.create).toHaveBeenCalled();
    expect(mockEmail.send).toHaveBeenCalledWith(
      expect.objectContaining({ to: 'john@example.com' })
    );
  });
});

Examples

实现的收益

Complete Refactoring Example

Before

javascript
// legacy-user-service.js - 200 lines of complex, coupled code
var UserService = {
  createUser: function(fn, ln, em, ph, addr) {
    if (!em || em.indexOf('@') === -1) {
      return { error: 'Invalid email' };
    }
    var conn = mysql.createConnection(config);
    conn.connect();
    conn.query(
      'INSERT INTO users (first_name, last_name, email, phone, address) VALUES (?, ?, ?, ?, ?)',
      [fn, ln, em.toLowerCase(), ph, addr],
      function(err, result) {
        if (err) {
          console.log(err);
          return { error: 'Database error' };
        }
        // Send welcome email
        var nodemailer = require('nodemailer');
        var transporter = nodemailer.createTransport(emailConfig);
        transporter.sendMail({
          to: em,
          subject: 'Welcome!',
          html: '<h1>Welcome ' + fn + '!</h1>'
        }, function(err, info) {
          if (err) console.log(err);
        });
        conn.end();
        return { id: result.insertId };
      }
    );
  }
};
  • 可测试性:依赖注入,易于模拟
  • 可读性:清晰、专注的方法
  • 可维护性:单一职责原则
  • 类型安全:TypeScript接口防止错误
  • 可复用性:组件可独立使用
  • 错误处理:适当的异常处理
  • 现代模式:Async/await、依赖注入

After

检查清单

typescript
// user-service.ts - Clean, testable, maintainable
interface UserData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address: string;
}

class UserService {
  constructor(
    private database: Database,
    private emailService: EmailService,
    private validator: Validator
  ) {}

  async createUser(userData: UserData): Promise<User> {
    this.validator.validateEmail(userData.email);

    const normalizedData = this.normalizeUserData(userData);
    const user = await this.database.users.create(normalizedData);

    await this.sendWelcomeEmail(user);

    return user;
  }

  private normalizeUserData(data: UserData): UserData {
    return {
      ...data,
      email: data.email.toLowerCase().trim()
    };
  }

  private async sendWelcomeEmail(user: User): Promise<void> {
    await this.emailService.send({
      to: user.email,
      subject: 'Welcome!',
      template: 'welcome',
      data: { firstName: user.firstName }
    });
  }
}

// validator.ts
class Validator {
  validateEmail(email: string): void {
    if (!email || !email.includes('@')) {
      throw new ValidationError('Invalid email format');
    }
  }
}

// Easy to test
describe('UserService', () => {
  it('should create user with valid data', async () => {
    const mockDb = createMockDatabase();
    const mockEmail = createMockEmailService();
    const service = new UserService(mockDb, mockEmail, new Validator());

    const user = await service.createUser({
      firstName: 'John',
      lastName: 'Doe',
      email: 'john@example.com',
      phone: '555-0123',
      address: '123 Main St'
    });

    expect(user.id).toBeDefined();
    expect(mockDb.users.create).toHaveBeenCalled();
    expect(mockEmail.send).toHaveBeenCalledWith(
      expect.objectContaining({ to: 'john@example.com' })
    );
  });
});
在认为重构完成前,请确认:
  • 所有现有测试通过
  • 为重构后的代码添加了新测试
  • 代码覆盖率保持或提升
  • 公共API无破坏性变更(或已适当记录)
  • 性能基准测试显示无退化
  • 代码评审已完成
  • 文档已更新
  • 重构决策已记录
  • CI/CD流水线通过
  • 分阶段部署以在类生产环境中验证

Benefits Achieved

支持建议

  • Testability: Dependencies injected, easy to mock
  • Readability: Clear, focused methods
  • Maintainability: Single responsibility principle
  • Type Safety: TypeScript interfaces prevent bugs
  • Reusability: Components can be used independently
  • Error Handling: Proper exception handling
  • Modern Patterns: Async/await, dependency injection
对于复杂的重构场景,建议:
  • 尽早并经常寻求同行评审
  • 使用功能标志进行逐步发布
  • 创建重构计划文档
  • 安排专门的重构时间
  • 部署后监控生产指标

Checklist

Before considering refactoring complete:
  • All existing tests pass
  • New tests added for refactored code
  • Code coverage maintained or improved
  • No breaking changes to public APIs (or properly documented)
  • Performance benchmarks show no regression
  • Code review completed
  • Documentation updated
  • Refactoring decisions documented
  • CI/CD pipeline passes
  • Staged deployment to verify in production-like environment

Support

For complex refactoring scenarios, consider:
  • Seeking peer review early and often
  • Using feature flags for gradual rollouts
  • Creating a refactoring plan document
  • Scheduling dedicated refactoring time
  • Monitoring production metrics after deployment