pcb-rnd knowledge pool
Programming tips: bail-out
prog_tip1 by Tibor 'Igor2' Palinkas on 2018-01-27 | Tags: dev, tips, programming, style, readable, simple, code |
Abstract: Code organization tips and tricks to get the code simpler and more readable: bail-out.
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:
- the validity check and the error handling stay together
- prefer the simple, flat logic where possible
- it is very easy to add or remove new checks, without having to introduce new levels
- even temporarily disabling a check, e.g. commenting it out, is much simpler
- as the code grows, functions often need to be split; the flat organization makes it simpler to split out a set of checks in a separate checker function (see below)
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; }