So I used to write codes like this:
if(condition1) {
if(condition2) {
if(condition3) {
// some tasks that are overwritten everywhere
} else {
}
} else {
}
}
And it is not only 3 layers, but many!
What are the issues of doing like this?
- Hard to follow: Huge blocks of code is very difficult to read.
- Difficult to maintain: After a time when coming back to the project again, I would not remember what I did because logic and functions overlapping each other everywhere. When I want to modify something or add new features it seems to be impossible.
- Looks really bad and stressful: Every time looking at this code I just want to ignore everything and go to sleep.
Here are some ways to fix this:
Write tasks into functions
Each tasks can be written into a function. This prevents code duplication and easy to follow what tasks are called in which conditions.
So the key point here is not to over-complicate your functions. Each function should only do one task, whether to validate or to get information.
No need to include “else” all the time
Just get rid of them to have peace of mind if you don’t know what to do in the else case.
Returns early
Returns when the conditions do not match. It is better than setting up the whole conditions block and includes an else for the case that does not match.
So, instead of the example code blocks above, it can be like, just for example:
if ( !check_security() ) {
// stop the program right when security check failed
return;
}
$user_input = get_user_input();
if ( empty($user_input) || !check_valid_input($user_input) ) {
// stop the program right when user inputs are invalid
return;
}
// this line only executes when all the conditions meet.
set_prefix($information);
// The functions list.
function check_security ( $args ) {
// returns true or false for security check
}
function get_user_input ( $args ) {
// return user inputs
}
function check_valid_input ( $args ) {
// returns true or false for user input validation
}
function set_prefix () {
// add prefix to the input, or modify the user input as you want
}
The benefits:
- Get rid of the annoying multi-layered nested functions.
- Tasks are written into functions so it is easier to debug or add features.
- Returns early so the program never has to execute codes before it realizes the case does not match.
- The code is cleaner and easier for team collaboration.