Live data from Hacker News

Avoid Else, Return Early (2013)

blog.timoxley.com

1–10 of 601 posts

Re: Avoid Else, Return Early (2013)

#2
I agree with much of the article (return early, errors management at the top, etc.). But won't returning a "wrong" value for the sake of one less line worsens the readability of the code?

When I saw that, I imagined myself spending 10 minutes trying to understand why he does that. But maybe I'm not familiar with a JS best practice here.

Re: Avoid Else, Return Early (2013)

#5
I would agree. Putting "early out" logic at the beginning allows the one who reads the code to lower the cognitive load a bit. Basically "I know I can read the following code safely because the error handling and parameter sanitizing is done". But that only works with mundane operations (error handling, parameters sanitizing). If the operations convey some important semantics, then I prefer to see the guarded code inside an if block...

Re: Avoid Else, Return Early (2013)

#8
post #3

"removing a whole line and more braces" - this is really fighting the wrong enemy. Code should be written in a way it is more readable, not shorter.

Exactly. This led to the famous OSX double goto bug [0]

  if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;
  ... other checks ...
  fail:
    ... buffer frees (cleanups) ...
    return err;
[0] https://www.dwheeler.com/essays/apple-goto-fail.html

Re: Avoid Else, Return Early (2013)

#10
post #2

I agree with much of the article (return early, errors management at the top, etc.). But won't returning a "wrong" value for the sake of one less line worsens the readability of the code? When I saw that, I imagined myself spending 10 minutes trying to understand why he does that. But maybe I'm not familiar with a JS best practice here.

returning a wrong result is definitely wrong. It conveys some unexpected meaning and side effects...
Post reply on HN