DEV Community

Discussion on: If/else or just if?

Collapse
 
somedood profile image
Basti Ortiz • Edited

I prefer the second syntax because it acts like a "guard" against further execution, so to speak. The first syntax just encourages more nesting and levels of indentations. To me, it is more readable to have a "guard" condition than to have if-else blocks.

Collapse
 
tyrw profile image
Tyler Warnock

I hadn't encountered the term "guard" for this but I like it a lot 👌

Collapse
 
somedood profile image
Basti Ortiz

I can't take the credit for it. 😉

Collapse
 
dexterstpierre profile image
Dexter St-Pierre

I have the same train of thought with it! A senior developer at a previous job introduced it to me

Collapse
 
pedrohba1 profile image
Pedro Bufulin

The first time I heard the term "guard" was in haskell. Is it any related?

Collapse
 
somedood profile image
Basti Ortiz

I'm quite surprised actually. Given the imperative nature of if statements, I wouldn't expect Haskell (of all languages) to be the origin of that term.

Thread Thread
 
fennecdjay profile image
Jérémie Astor

Haskell (among other functional languages, I guess) has guards for pattern matching

sign x |  x >  0        =   1
       |  x == 0        =   0
       |  x <  0        =  -1
Collapse
 
immathanr profile image
Mathan raj

I call it the Short-circuit or (Fast-fail)[en.m.wikipedia.org/wiki/Fail-fast]. It will help you just worry about less things if it's not followed by else