DEV Community

Discussion on: Why we shouldn't use "else"

Collapse
 
phlash profile image
Phil Ashby

I generally follow a similar pattern, which is also known as 'early return' and nicely explained here by Szymon: szymonkrajewski.pl/why-should-you-...

What matters to me is that there is a common pattern to functions across a codebase, so the reader (hello you in 15 months time) can see the 'happy path' easily, and can see the priority of unhappy conditions, which communicates what matters more too.

Use of assertions or guard conditions also results in a similar pattern for good reason :)

Collapse
 
jamesthomson profile image
James Thomson

I've been using this method for years now and can definitely say it makes code far more legible and concise. If/else has it's place at times, but I really think (and hope) that early returns should be taught as a standard practice.

Collapse
 
scott_yeatts profile image
Scott Yeatts

I once argued AGAINST early return, but then I tried it and I can't imagine why I didn't use it before.

Early on in my career (a long time ago in a galaxy far far away and all that) I had been taught a rule that a function should only ever have one return in order to make it clear what was being returned, and I clung to that rule for too long.

It's one of the best changes I've made to my code style in years. I love it.

Collapse
 
patricktingen profile image
Patrick Tingen • Edited

I was taught exactly the same thing, but when you adhere to that you end up with massive blocks. Early return is king!