Very often the code needs to check a lot of things to make sure the final operation it needs to perform will not fail. First the classic, positive construction of these conditions, then the bail-out version:
/* classic */ function do_something() { prepare1; if (valid1) { prepare2; if (valid2) { prepare3; if (valid3) doit; else error3; } else error 2; } else error1; }
/* bail out */ function do_something() { prepare1; if (!valid1) { error1; return; } prepare2; if (!valid2) { error2; return; } prepare3; if (!valid3) { error3; return; } doit; }
Pros for the bail-out structure:
function layer_checks() { prepare2; if (!valid2) { error2; return bad; } prepare3; if (!valid3) { error3; return bad; } return good; } function do_something() { prepare1; if (!valid1) { error1; return; } if (!layer_checks()) return; doit; }