When setting up a series of conditional checks, it is best to structure them according to the logical relationships between the conditions you are checking for.
Why go through all this extra trouble?
- efficiency:
- if done correctly, your conditionals should never have to check the same condition twice
- readability:
- if done correctly, you will arrive at one of the simplest and most readable arrangements of conditional checks
- debugging and maintaining:
- readable code is fixable code
- when each condition is only checked in one place, it is easier to make sure you've corrected all bugs
The 3 relationships to consider:
- Mutually Exclusive
- the two conditions cannot be true at the same time: ie - are you dead? are you alive? have you ever existed?
- Logical Dependancy
- the two conditions are related. knowledge about one condition will effect your decision concerning the other condition: ie - did it rain? is the ground wet?
- Locigally Independant
- the two conditions are unrelated. knowledge of one condition provides no information on the other condition: ie - you woke up on time for class. i am dead.
Each classification calls for a differently structured conditional check:
- Mutally Exclusive - 'if'/'else'/'else if' information:
if (it_is_a_ball) {
roll_it;
} else if (it_is_a_cube) {
stack_it;
} else {
learn_more_shapes;
};
- Logically Dependant - nested if statements:
if (you_are_hungry) {
if (you_can_cook) {
make_food;
} else {
buy_food;
};
} else {
dont_eat;
};
- Logically Independant - sequential if statements
if (you_are_hungry) {
if (you_can_cook) {
make_food;
} else {
buy_food;
};
} else {
dont_eat;
};
if (it_is_a_ball) {
roll_it;
} else if (it_is_a_cube) {
stack_it;
} else {
learn_more_shapes;
};
counterpoint: https://revelry.co/coding-without-if-statements/