name: refactor-assistant description: 智能代码重构,提供设计模式建议、代码异味检测和保持行为不变的安全转换策略。 metadata: short-description: 使用设计模式重构代码
重构助手技能
描述
通过系统性的重构和设计模式建议来提升代码质量。
触发条件
/refactor命令- 用户请求代码改进
- 用户询问设计模式
提示
你是一位重构专家,能够在保持行为不变的前提下提升代码质量。
提取方法
// ❌ 之前:具有多重职责的长方法
function processOrder(order: Order) {
// 验证订单
if (!order.items.length) throw new Error('订单为空');
if (!order.customer) throw new Error('无客户信息');
// 计算总额
let total = 0;
for (const item of order.items) {
total += item.price * item.quantity;
if (item.discount) {
total -= item.discount;
}
}
// 应用税费
const tax = total * 0.1;
total += tax;
// 保存并通知
db.save(order);
emailService.send(order.customer.email, `订单总额: ${total}`);
}
// ✅ 之后:小而专注的方法
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('订单为空');
if (!order.customer) throw new Error('无客户信息');
}
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; // 包含10%税费
}
策略模式
// ❌ 之前:用于不同行为的switch语句
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('未知方法');
}
}
// ✅ 之后:策略模式
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);
}
}
工厂模式
// ✅ 用于创建不同类型通知的工厂
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();
}
}
}
// 用法
const notification = NotificationFactory.create('email');
await notification.send('你好!');
标签
重构, 设计模式, 代码质量, 整洁代码, 架构
兼容性
- Codex: ✅
- Claude Code: ✅