The nested ‘if’ statements make our code harder to read and understand. Consider the following code. It might be very simple but is very hard to read.
function showAdminPanel(){ if(wifiConnected){ if(loggedIn){ if(isAdmin){ loadAdminPanel(); } else { echo "Must be an administrator"; } } else{ echo "Must be logged in"; } } else { echo "Must be connected to the wifi"; } }
Instead of nesting the ‘if’ statements, use the Guard Clauses technique to improve the readability of your code. A guard clause is simply a check that immediately exits the function, either with a return statement or an exception. If we apply this technique our code becomes very easy to understand.
function showAdminPanel(){ if(!wifiConnected){ echo "Must be connected to the WiFi"; return; } if(!loggedIn){ echo "Must be logged in"; return; } if(!isAdmin){ echo "Must be an administrator"; return; } loadAdminPanel(); }
Now you can add any number of conditions without ever nesting again.