Follow

My favorite programming trick.

> With the early `return` pattern, you check for the opposite of the thing you want, and `return` early to end the function when that’s the case.

> This reduces nested `if` statements, and makes your code a bit easier to read.

gomakethings.com/the-early-ret

(jan.boddez.net/notes/b5803e983)

@jan this is one of my favorite ways to refactor old code. Never heard it called the “early return.” I usually call it a “short circuit.”

@jan still don't know why more people don't automatically do this. So much code is so unreadable

@oiyouyeahyou Well, it takes a little getting used to as well. At first, in long procedural-style scripts, nested `if`s might make more sense, but the more things are split off into separate functions, the more you start benefiting from early returns. Very rarely do I write `if` statements that are more than one level deep. Heck, I barely use `else` anymore!

Sign in to participate in the conversation
Mastodon

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!