|
|
|
|
|
by kazinator
602 days ago
|
|
> you can glance at the nesting to see which ones affect the line you want to edit, and ignore the others. Only if all the cases return! Only then is it obvious that you have independent cases. E.g. suppose we have three Boolean inputs x, y, z and want to do something for each binary combination: if (x) {
if (y) {
if (z) {
return 7;
} else {
return 6;
}
} else { // x && !y
if (z) {
return 5;
} else {
return 4;
}
}
} else { // !x
if (y) { // !x && y
if (z) {
return 3;
} else {
return 2;
}
} else { // !x && !y
if (z) {
return 1;
} else {
return 0;
}
}
}
How would this look with early returns? One obvious way: if (x && y && z)
return 7;
if (x && y && !z)
return 6;
if (x && !y && z)
return 5;
// ... etc
(Let's ignore that we can just calculate the output with some bit twiddling; that's not the point).Early return can be very clear, if we can bear repeatedly testing some conditions. |
|
My comment was about using if blocks as opposed to early returns. I.e. where the nested ifs run exhaustively and return afterwards.
Also, obviously deep nested ifs aren't good, so I wasn't advocating them - I just think it's better to fix them by splitting functions or simplifying control flow, than by adding early returns.