Huzaifa Rasheed

Huzaifa Rasheed

Software Engineer

Blogs

2 Simple Tips To Clean Nested IF/ELSE Conditions.

Posted on March 30, 2021

Repost of https://dev.to/rhuzaifa/2-simple-tips-to-clean-nested-if-else-conditions-2kn4

There might be a time when you have your if/else conditions like this

if(age>0){
	if(age < 18){
		return "Not an Adult"
	}
	else if (age >= 18 && age<60){
		return "An Adult"
	}
	else{
		return "Senior Citizen"
	}
}
else{
	return "Age must be a valid number"
}

This is however a simple example, this can get messy as your code logic gets complex.

To add more, Multiple nested if/else increases Cyclomatic complexity and it is better to avoid it whenever possible.

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code. Thomas J. McCabe, Sr.

So what can you do to avoid it? Simple, Try to have fewer branches of if/else conditions achievable with the following tips.

The Tips

  1. Guard Clauses
  2. Ternary Operators

There are others like Switch Statement, Dictionaries, Jump Tables, etc. but those are beyond this article’s scope.

1. Guard Clauses

In simple terms, return early if a condition is not met. Again taking our previous code, we can modify it like this

// Guard clause
if(age <= 0){
	return "Age must be a valid number" 
}

if(age < 18){
	return "Not an Adult"
}
else if (age < 60){
	return "An Adult"
}

return "Senior Citizen"

Or you could even do this

// Guard clause
if(age <= 0) return "Age must be a valid number"

if (age < 18) return "Not an Adult"
else if (age < 60)	return "An Adult"
else return "Senior Citizen"

Use brackets or not, scoped only to clean code.

2. Ternary Operators

Most of you already use them, but anyways. Modifying our last code

if(age <= 0) return "Age must be a valid number"

var res = (age < 18 ? "Not an Adult" 
		: (age < 60) ? "An Adult" 
		: "Senior Citizen")

return res

or

if(age <= 0) return "Age must be a valid number"

return (age < 18 ? "Not an Adult" : (age < 60) ? "An Adult" : "Senior Citizen")

Disclaimer: Clean code doesn’t always mean Performant code or Simple Code. Sometimes you have to decide between one or the other. There is however a limit to how clean you can make your code.


So here it is guys, do you use any other method to clean nesting? Be sure to tell me in the comments.