Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Created May 23, 2020 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raineorshine/0d1dea1eb40f3cc059ec6af49f701fa6 to your computer and use it in GitHub Desktop.
Save raineorshine/0d1dea1eb40f3cc059ec6af49f701fa6 to your computer and use it in GitHub Desktop.
Why multiple return statements should be avoided

Note the following code:

if (a) {
  foo()
  bar()
}
else {
  foo()
  moo()
}

Obviously there is redundancy here, and this code could be more simply expressed as:

foo()
if (a) {
  bar()
}
else {
  moo()

Not only does it reduce redundancy, but it is easier to read, because the case statements only contain the parts that are different, that are switched via the condition.

Multiple return statements is the same problem.

if (a) {
  return bar()
}
else {
  return moo()
}

The return keyword is present in both cases. It does not depend on the condition at all. Why include it in the cases when it is not conditional? It is less redundant, more consistent, and cleaner to factor it out. Here is some pseudo-code that is not valid Javascript, but demonstrates the minimal refactoring move:

return(
  if (a) {
    bar()
  }
  else {
    moo()
  }
)

Of course the above won't work because if statements are procedural not functional in Javascript. They themselves do not evaluate to anything. Luckily, we have the ternary operator:

return a
    ? bar()
    : moo()

Less code, less redundancy, cleaner cases. In fact, this looks much closer to the case statements used in purely functional programming languages like lisp, haskell, or purescript. A novice will be confused by the syntax. Someone who knows the syntax well, is rewarded by the easy readability of factoring the unconditional return statement out of the conditional.

It is less readable to some people because there is a learning curve. Code appears to be less readable when either it is poorly structured or it is structured in an unfamiliar way. The difference is critical. Poorly structured code should be simplified to make it more readable. New structures of code should be learned to make it more readable. Ternary statements are just as easy to read, if not easier to read, than if statements once they become familiar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment