Stop using if else in your code !!
Tricks how to simplify if else or switch case in your code …
A high-level programming language statement that compares two or more sets of data and tests the results. If the results are true, the THEN instructions are taken; if not, the ELSE instructions are taken.
The following is a BASIC example:
10 if answer = "y" then print "Yes"
20 else print "No"
In many languages, THEN is implied. All statements between IF and ELSE are carried out if the condition is true. All statements between ELSE and the end of the statement are carried out if not true.
The following dBASE and C/C++ examples produce the same results as above:
dBASE C/C++
if answer="y" if (answer =='y')
? "Yes" {
else printf ("Yes\n");
? "No" else
endif printf ("No\n");
}
A typical if else statement would appear similar to the one below (this example is JavaScript, and would be very similar in other C-style languages).
var x = 1;
if (x === 1) {
window.alert("The expression is true!");
}
else {
window.alert("The expression is false!");
}
In this case, with the variable x being equal to the number 1, the statement in the first set of curly braces {} is executed. You would receive a pop-up “The expression is true!” alert message. If you were to change the first line of the above code to var x = 42;, you would receive a pop-up alert message with the text “The expression is false!”
This is code that is easy to read if it has very few ramifications in the code
And that would be a big problem if a lot of conditions were applied to the code.
I will show a simple example like this in go lang.
See online for this simple calculation requires a lot of if and else and same as we use switch case condition like this code.
Then what if there are new conditions that will continue to increase as needed ???
I will propose a simpler way using the hash table function.
In go it is called the map function then in python it is usually called a dictionary, it will showing like this.
The code will look simple and will be easy to maintain, no matter how many conditions it will need, we will only focus on the hash tables. In python even looks more simple and elegant :D
Summary:
So by utilizing the hash table function to perform condition branching, this will be very helpful and easy to work on code that requires many conditions in the code besides that the code will be easily maintained.
Reference: