If-Else Visualization: Refactor Complex Conditions Fast
2026-06-18
The Problem with Nested If-Else
Nested conditionals are the leading cause of code complexity. They create hidden paths, make testing difficult, and are a common source of bugs. Let's refactor two real-world examples.
Example 1: Discount Calculation
**Before — deeply nested:**
function calculateDiscount(user) {
let discount = 0;
if (user.isMember) {
if (user.years > 5) {
if (user.hasCoupon) {
discount = 0.4;
} else {
discount = 0.3;
}
} else {
if (user.hasCoupon) {
discount = 0.25;
} else {
discount = 0.15;
}
}
} else {
if (user.hasCoupon) {
discount = 0.1;
} else {
discount = 0;
}
}
// Seasonal bonus
if (discount > 0) {
const month = new Date().getMonth();
if (month >= 11 || month <= 1) {
discount += 0.05;
}
}
return Math.min(discount, 0.5);
}
**After — early returns + lookup table:**
function calculateDiscount(user) {
const baseDiscounts = {
"member_5plus_coupon": 0.4,
"member_5plus": 0.3,
"member_coupon": 0.25,
"member": 0.15,
"coupon": 0.1,
};
const key = [
user.isMember ? "member" : "",
user.years > 5 ? "5plus" : "",
user.hasCoupon ? "coupon" : "",
].filter(Boolean).join("_");
let discount = baseDiscounts[key] || 0;
// Seasonal bonus
if (discount > 0) {
const month = new Date().getMonth();
if (month >= 11 || month <= 1) {
discount += 0.05;
}
}
return Math.min(discount, 0.5);
}
Example 2: User Role Access Check
**Before — nested switch:**
function checkAccess(user, resource) {
if (user && user.roles) {
switch (user.role) {
case "admin":
return true;
case "editor":
if (resource.type === "article") return true;
if (resource.type === "comment" && resource.authorId === user.id) return true;
return false;
case "viewer":
if (resource.isPublic) return true;
return false;
default:
return false;
}
}
return false;
}
**After — strategy pattern:**
const accessRules = {
admin: () => true,
editor: (resource, user) =>
resource.type === "article" ||
(resource.type === "comment" && resource.authorId === user.id),
viewer: (resource) => resource.isPublic,
};
function checkAccess(user, resource) {
if (!user?.roles?.length) return false;
const rule = accessRules[user.role];
return rule ? rule(resource, user) : false;
}
Why These Refactors Work
1. **Eliminate nesting** — Every indent level doubles the mental load 2. **Single responsibility** — Each function or rule handles one concern 3. **Testable in isolation** — Extract rules into pure functions that are trivial to unit test 4. **Self-documenting** — The strategy object names describe the logicTry the If-Else Refactor Tool
Use the If-Else Refactor Tool on YZIF to automatically transform your nested if-else code. Paste your code, choose your target style (early return, switch, or strategy pattern), and get clean code instantly.