Stop using ELSE statements - Try this instead

Published 2020-10-04
Always use a guard clause instead of ELSE statements. The other day I came across a Medium article that said - STOP USING ELSE statements in your programs. I did some research and found some other articles having similar content.

In this video, I'm explaining why you should always try to avoid using else statements in your code. You can always replace them with Guard clauses. Watch the video to find out more. I will be posting another video with a technique explaining how we can avoid If-conditions as well.

References
------------------
medium.com/better-programming/why-you-need-to-stop…

en.wikipedia.org/wiki/Guard_(computer_science)

medium.com/edge-coders/coding-tip-try-to-code-with…

medium.com/javarevisited/java-write-code-thats-mod…

medium.com/@janalmazora/how-to-prevent-using-if-el…

medium.com/@jamousgeorges/dont-use-else-66ee163dea…

medium.com/swlh/stop-using-if-else-statements-f4d2…

Music credits: www.bensound.com/

If you enjoyed watching this video, please consider to like and subscribe as well, so I can keep working on more videos like this. Have a nice day!

All Comments (16)
  • @bits-of-bass
    I'll give this a thumbs up even before watching it. I've been using guard clauses for nearly 20+ years, and they really clean up conditional logic. They're particularly useful when used as precondition checks, so by the time you get to the core of some logic, you know the exact state of the data. Guard clauses => easier to read, easier to test, more bulletproof code!
  • Interesting, but doesn’t allow for factored logic (which is acknowledged in the video). You could do the same thing. In a try-except, raising a benign exception to hop out of a stack of non-nested if statements.
  • @delcarmat
    thank you for this video I'm learning JS and this is very helpful
  • In practice I don't find the need to use else statements in most cases. A lot of if statements are meant to exit the code early. I tend to keep nesting to a minimum because it makes code more readable. I also find out in a recent project I could remove some guard clauses that would throw in the beginning of a method by putting the error checking code inside the input object. It was an immutable object and error checking occured in the constructor. That made it very clean.
  • so, guard clauses mean writing a bunch of if condition without nesting it, right?
  • @TarekFaham
    Total stupidity... No way you can avoid using else. To avoid the if statements hell you need to use decision tables approach.