I have the following code in Java:
public void doSomething(int i) {
if (i == 12) {
// order should be same
up();
left();
stop();
}
if (i == 304) {
// order should be same
right();
up();
stop();
}
if (i == 962) {
// order should be same
down();
left();
up();
stop();
}
}
// similar code can be done using switch case statements.
// all the function can have any functionality and might not resemble to the name given to them.
Now if I am asked not to use either of if-else and switch case statements, then what can be done? The code can be done in either Java or JavaScript.
The conditional operator (or Ternary operator) is an alternative for 'if else statement'.
Check the Testing Expression: An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
Most would consider the switch statement in this code to be more readable than the if-else statement. As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large.
A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
If you can use JavaScript, you can use a object with functions:
function doSomething(i) {
var obj = {};
obj[12] = function () {
// order should be same
up();
left();
stop();
};
obj[304] = function () {
// order should be same
right();
up();
stop();
};
obj[962] = function () {
// order should be same
down();
left();
up();
stop();
};
// apparently we can't use any conditional statements
try {
obj[i]();
} catch (e) {}
}
If only if
and switch
statements aren't allowed, replace all the if
statements with the logical AND operator (&&
):
function doSomething(i) {
(i == 12) && (
// order should be same
up(),
left(),
stop()
);
(i == 304) && (
// order should be same
right(),
up(),
stop()
);
(i == 962) && (
// order should be same
down(),
left(),
up(),
stop()
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With