This is the practice of preventing code from becoming too long horizontally. When too much code is nested, the text we need to navigate horizontally grows to be unmanageable.
Two techniques we use to reduce nesting are:
- Extraction
- Inversion
Extraction
In extraction, we extract a block of code and place it within a function. We then call that function from where the code block used to be.
#include <stdio.h>
// checking feature extracted out as function
void even_or_odd(int x){
if (x%2==0){
printf("%d is even\n",x);
}else{
printf("%d is even\n",x);
}
}
int main(){
// without extraction
for (int x=0;x<10;x++){
if (x%2==0){
printf("%d is even\n",x);
}else{
printf("%d is even\n",x);
}
}
// with extraction
for (int x=0;x<10;x++){
even_or_odd(x);
}
return 0;
}
Inversion
In inversion, we write guard clauses instead of nesting a bunch of conditional statements. We place the most common behaviour and place condition checks before it to prevent (guard) unwanted states from reaching that common behaviour.
We place the guard clauses before the common behaviour because the code is executed from top to bottom.
#include <stdio.h>
int main(){
int age;
printf("Please enter your age: ");
scanf("%d",&age);
// without inversion
if (age>=18){
printf("You are an adult\n");
if (age>=65){
printf("You are also a senior citizen\n");
}
}
else{
printf("You are not an adult\n");
}
// with inversion
if (age>=65){
printf("You are an adult\n");
printf("You are also a senior citizen\n");
return 0;
}
if (age>=18){
printf("You are an adult\n");
return 0;
}
printf("You are not an adult\n");
return 0;
}
Notice that we cater for the exceptions (when the person is at least 65 and when the person is at least 18). We use return to prevent the code from ever reaching the printf(“You are not an adult\n”).