Hacker News new | past | comments | ask | show | jobs | submit login

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



IMO 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.


Maybe. Or maybe it is not obvious with a small example. Not sure about the anti-pattern, but I'm sure an anti-conventional coder ;-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: