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

  if (a) {
    do_something();
    return;
  } else if (b) {
    do_something();
    if (something_else() == -1) {
      return;
    }
  }
  
  do_other_things();
  
  maybe_exit_here();
  
  maybe_keep_going();
it has similarity to frequent `goto label` type of coding



I'd argue that this sort of thing is fine, as long as the `return` is not nested deeply. A function which starts with a list of 'early exit' simple conditions is fairly easy to deal with, compared with one where you need to read the whole thing to check that the value assigned to the returned variable isn't reassigned later in a different condition. Early returns can significantly reduce cognitive load if used correctly precisely because they exit directly.

Once you have complex bail-out scenarios, the function needs breaking up or insanity follows... but that's true of any sufficiently confusing decision tree.

Generally I have found `else` to be something of an antipattern. I usually find it cleaner to write the code as 'this special early bail-out with a return, and the other case is just the rest of the function'. A bit like pattern-matching in Haskell, or a `switch` block in which the default case is the usual one. I also try to avoid reassigning variables, eg. in Typescript everything would be `const`.

But like all generalities, these have exceptions!


GOTO return(); is the droid you're looking for. :)




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

Search: