Never Nesting by Nev R. Nester
Source: Dev.to
Never Nesting
Never Nesting is essentially a recommendation to avoid nesting deeper than three indentation levels.
… if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program.
— Linus Torvalds
void process_order(User *u, Order *o, Payment *p) {
if (u != NULL) {
if (o != NULL) {
if (p != NULL) {
if (!u->is_banned) {
if (o->total > 0) {
if (check_inventory(o)) {
if (p->balance >= o->total) {
if (execute_payment(u, o, p)) {
if (finalize_order(o)) {
if (send_receipt(u)) {
printf("Success\n");
} else {
log_error("Receipt failed");
}
} else {
log_error("Finalize failed");
}
} else {
log_error("Payment failed");
}
} else {
log_error("Insufficient funds");
}
} else {
log_error("Out of stock");
}
} else {
log_error("Order empty");
}
} else {
log_error("User banned");
}
} else {
log_error("No payment info");
}
} else {
log_error("No order info");
}
} else {
log_error("No user info");
}
}This example looks absurd. Deeply nested if statements or loops become hard to follow, making the code feel intentionally obfuscated.
A more realistic snippet illustrates the same problem:
// calculator function
int calculate_final(int a, int b, char op) {
if (a != 0) {
if (b != 0) {
if (op == '+') {
return a + b;
} else {
if (op == '-') {
return a - b;
} else {
return 0;
}
}
} else {
return -1;
}
} else {
return -1;
}
}Extraction
Extraction is a technique under Never Nesting that moves portions of code into separate functions, reducing nesting depth.
int is_invalid(int a, int b) {
return (a == 0 || b == 0);
}
int calculate_final(int a, int b, char op) {
if (is_invalid(a, b)) {
return -1;
}
if (op == '+') {
return a + b;
if (op == '-' {
return a - b;
}
}
return 0;
}Here the first condition is extracted into is_invalid, simplifying the main function.
Guard Clauses
Guard clauses handle “bad” or edge cases early, allowing the rest of the function to assume valid data. Using the is_invalid helper as a guard reduces indentation dramatically.
int is_invalid(int a, int b) {
return (a == 0 || b == 0);
}
int calculate_final(int a, int b, char op) {
if (is_invalid(a, b)) {
return -1;
}
if (op == '+') {
return a + b;
}
if (op == '-') {
return a - b;
}
return 0;
}Should I always Never Nest?
It’s impossible to never nest past three levels, but keeping nesting shallow improves readability. When code starts to look overly nested, it’s a signal to refactor—extract methods, introduce guard clauses, or rethink the algorithm. Flat, readable code is easier to maintain and less likely to bite you later.