evermos-tech

Evermos Product + Engineering + Data. Fresh from our desks everywhere.

Follow publication

Stop using Nested If! Try Guard Clauses instead

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 :

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

evermos-tech
evermos-tech

Published in evermos-tech

Evermos Product + Engineering + Data. Fresh from our desks everywhere.

Cevin Ways
Cevin Ways

Written by Cevin Ways

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

Responses (1)

Write a response