如何清理嵌套的 If-Else 语句
2026-05-30
嵌套 If-Else 的问题
深层嵌套的 if-else 语句是代码复杂性最常见的来源之一。它们使代码难以阅读、测试和维护。以下是三种实用的清理技术。
1. 提前返回(卫语句)
与其嵌套条件,不如在满足条件时提前返回:
// 重构前
function getDiscount(age, isMember) {
if (isMember) {
if (age > 65) {
return 0.3;
} else {
return 0.2;
}
} else {
if (age > 65) {
return 0.1;
} else {
return 0;
}
}
}
// 重构后
function getDiscount(age, isMember) {
if (isMember && age > 65) return 0.3;
if (isMember) return 0.2;
if (age > 65) return 0.1;
return 0;
}
2. Switch / Match 表达式
当检查同一个变量对应多个值时,使用 switch 或模式匹配:
// 重构前
function getRole(role) {
if (role === "admin") return "Full Access";
else if (role === "editor") return "Edit Access";
else if (role === "viewer") return "Read Only";
else return "No Access";
}
// 重构后
function getRole(role) {
switch (role) {
case "admin": return "Full Access";
case "editor": return "Edit Access";
case "viewer": return "Read Only";
default: return "No Access";
}
}
3. 多态 / 策略模式
对于复杂的条件逻辑,用多态替代条件判断:
const strategies = {
admin: () => "Full Access",
editor: () => "Edit Access",
viewer: () => "Read Only",
};
function getRole(role) {
return (strategies[role] || (() => "No Access"))();
}
亲自尝试
使用 YZIF 的 If-Else 重构工具 自动将你的嵌套 if-else 代码转换为更清晰的替代方案。