</>YZIF
博客

每个开发人员都应掌握的 5 种代码重构技巧

2026-06-18

为什么重构很重要

重构是在不改变代码行为的前提下改进代码的艺术。它保持代码库健康,减少 bug,并加速未来的变更。

1. 提取方法

当一个函数做的事情太多时,将其部分逻辑提取为命名方法:

// 重构前:一个函数做所有事
function processOrder(order) {
// 验证
if (!order.items || order.items.length === 0) throw new Error("空订单");
if (!order.customer.email) throw new Error("缺少客户邮箱");
// 计算
let total = 0;
for (const item of order.items) {
total += item.price * item.quantity;
}
const tax = total * 0.08;
const finalTotal = total + tax;
// 发送
sendEmail(order.customer.email, "订单确认", `总计: $${finalTotal}`);
return finalTotal;
}

// 重构后:拆分为聚焦方法
function processOrder(order) {
validateOrder(order);
const total = calculateTotal(order);
sendConfirmation(order.customer.email, total);
return total;
}

function validateOrder(order) {
if (!order.items?.length) throw new Error("空订单");
if (!order.customer?.email) throw new Error("缺少邮箱");
}

function calculateTotal(order) {
const subtotal = order.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return subtotal * 1.08; // 8% 税
}

2. 用卫语句替换嵌套条件

深层嵌套会掩盖逻辑。提前返回:

// 重构前
function processPayment(payment) {
if (payment) {
if (payment.amount > 0) {
if (payment.method === "credit_card") {
return chargeCard(payment);
} else {
return "不支持的支付方式";
}
} else {
return "无效金额";
}
} else {
return "未提供支付信息";
}
}

// 重构后
function processPayment(payment) {
if (!payment) return "未提供支付信息";
if (payment.amount <= 0) return "无效金额";
if (payment.method === "credit_card") return chargeCard(payment);
return "不支持的支付方式";
}

3. 用多态替换条件判断

使用对象查找替代 switch-on-type:

// 重构前
function calculateShipping(method, weight) {
if (method === "standard") return weight * 0.5;
if (method === "express") return weight * 1.5 + 5;
if (method === "overnight") return weight * 3 + 10;
return weight * 0.5;
}

// 重构后
const shippingRates = {
standard: (w) => w * 0.5,
express: (w) => w * 1.5 + 5,
overnight: (w) => w * 3 + 10,
};

function calculateShipping(method, weight) {
return (shippingRates[method] || shippingRates.standard)(weight);
}

4. 分解复杂条件

将复杂的 if 语句拆分为命名变量:

// 重构前
if (user.age >= 18 && user.country === "US" && !user.isBanned && user.verifiedEmail) {
grantAccess(user);
}

// 重构后
const isAdult = user.age >= 18;
const isUSResident = user.country === "US";
const isGoodStanding = !user.isBanned && user.verifiedEmail;

if (isAdult && isUSResident && isGoodStanding) {
grantAccess(user);
}

5. 合并重复条件

// 重构前
if (isSpecialDay) {
price = basePrice * 0.9;
notification = "特价折扣已应用!";
}
if (isSpecialDay) {
logEvent("special_discount");
}

// 重构后
if (isSpecialDay) {
price = basePrice * 0.9;
notification = "特价折扣已应用!";
logEvent("special_discount");
}

尝试 If-Else 重构工具

使用 YZIF 的 If-Else 重构工具 自动将嵌套的条件语句转换为清晰的卫语句、switch 语句或策略模式。