Stop using Nested If! Try Guard Clauses instead

Cevin Ways
evermos-tech
Published in
2 min readSep 30, 2022
Nested If in Real Life

Have you ever faced a situation where you had to use conditions to solve a problem? what you use most often is to use if or switch conditions?. When dealing with complex conditions you will definitely use nested if conditions, maybe that’s a good idea in the short term, and you think it is good for you when the deadline is on your eyes, but is your code easy to read, or will it make it difficult for you or other programmers to understand it one day?.

Of the problems above, then Guard Clauses Technique are the solution. guard clauses are not much different from if conditions, the difference lies in the approach. The approach is to invert the logic and process flow where we return every condition false or additional process, and at the end of the statement we set the condition true or normal process, the goal is to make the code more concise and easy to understand.

this is the example using nested if (no guard clauses) :

let’s implement the guard clauses, invert the logic by putting the exception throwing statements inside of these if statements. then this is what’s look like :

remember, writing good code is not an easy thing, writing good code means that it can be read by you and also other people who one day contribute to the code you create.

Notes : if u have any comment or feedback don’t hesitate to put in on comments section, thank you 🙏 .

Don’t Forget to connect w/ me on :

--

--

Cevin Ways
evermos-tech

Software engineer 👾 | Flutter Dev 🦉 | Tech Enthusiast 👨🏻‍💻