3 ms·
Avoid deep nesting by testing error case first and exiting/returning immediately. Instead of : If foo then bar Else baz Endif Now I write: I
by hamdouni 3y ago
Avoid deep nesting by testing error case first and exiting/returning immediately.
Instead of :
If foo then
bar
Else
baz
Endif
Now I write:
If foo then
bar
return
Endif
baz
Exit early makes the code easier to read and understand
- nivertech 3y agoIMO the example you provided is an anti-pattern. There are better ways to avoid deeply nested code, but it depends on the programming language. I try to make each method/function to have a single entry and a single exit. Cond, case, pattern maching in function heads, decision tables, and syntactic sugar in some PLs, allow you to flatten the nested code / branchinbg / conditionals.
- hamdouni 3y agoMaybe. Or maybe it is not obvious with a small example. Not sure about the anti-pattern, but I'm sure an anti-conventional coder ;-)