DEV Community

Discussion on: DevTips: Use early returns to avoid nested conditions

Collapse
 
stephenmirving profile image
Stephen Irving • Edited

What about using ternaries so you only need a single return statement instead of three? More DRY, less code, as well as being faster to scan, read, and understand in my opinion. Should never have more than one return statement for a function if it can be easily avoided.

render() {
  const personToLookFor = 'Thierry',
        [result, loading] = doesPersonExists();

  return (
    loading
      ? 'Loading...'
      : `${personToLookFor} ${result ? 'already exists' : 'doesn\'t exist.'}.` 
  );
}
```



Enter fullscreen mode Exit fullscreen mode
Collapse
 
thomasjunkos profile image
Thomas Junkツ • Edited

This ( »using ternaries« ) is in principle a good idea (I just posted my example and saw yours just now).

But have in mind that every branch adds more reading complexity.

If you use a ternary as a short form for when then it's from my POV okay - you are dealing with a binary outcome.

But when you nesting ternaries, you end up with

when then when then

which is harder to digest - which I tried to visualize by verbalizing it this way ;)

As a developer, I want to read as less code as necessary to understand what is going on. So your solution optimizes for that.

OTOH as a developer, I want to reason as less as possible as what a code is doing in case it has bugs. Taking that into account, I find your solution less favourable.

P.S.:

Or to contrast it with my own solution: I choose a similar approach like yours but added the guarding if-clause as a visual indicator of This is the uninteresting part. Nothing to see here. And the evalutation of the result which is from its nature a binary result (unless we are maybe at the quantum level) we have or we have not knowledge of a personToLookFor. And this binary result is explicitely written down as returning the result with the help of ternaries.