Letβs be honest, how many times you found yourself in situations like this:
void someMethod() {
if (condition1) {
if (condition2) {
if (condition3) {
doSomething();
} else {
debugPrint('Problem 3');
}
} else {
debugPrint('Problem 2');
}
} else {
debugPrint('Problem 1');
}
}
Countless times, perhaps even worse than that, especially at the beginning of our developer careers. The more conditions you nest, the more your code will get like this:
void someMethod() {
if (condition1) {
if (condition2) {
if (condition3) {
if (condition4) {
if (condition5) {
if (condition6) {
if (condition7) {
if (condition8) {
doSomething();
It can get pretty ugly and make the code reading process very frustrating. There is a better, more intuitive and read-friendly way to do it.
Guard Clauses
A guard clause consists of an expression that must evaluate whether code execution should continue. In a nutshell, instead of nesting multiple if conditions one inside another, we create guard clauses that individually checks if there is a problem before executing the main code. Letβs have a look at the transformation from the example above to the guard clauses technique:
void someMethod() {
if (!condition1) {
debugPrint('Problem 1');
return;
}
if (!condition2) {
debugPrint('Problem 2');
return;
}
if (!condition3) {
debugPrint('Problem 3');
return;
}
doSomething();
return;
}
Much more readable right?
Now is much simpler to add new conditions without messing up the code.