Ad hoc branching using if statements more than one level deep should be considered evil. “So if this and that, but not this other thing, unless that, then we do this… okay I get it”. They are seriously confusing and mentally draining to reason about, which means they are a breeding ground for bugs.
What to do if you really need to do nested ad hoc branching? Break the nested code out into its own function, restructuring the code in such a way that this refactoring is natural, not artificially forced. Breaking code into a function introduces a level of indirection, which increases cognitive overhead. But it also puts a box around this block of code, and gives it a meaningful name, which improves readability at the call site, and allows the reader to reason about the implementation of the function in isolation, which has a comparatively smaller cognitive overhead.
Comments
Post a Comment