Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative of if-else and switch statements

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.

like image 736
Shrikant Kakani Avatar asked Apr 09 '14 05:04

Shrikant Kakani


People also ask

What can I use instead of if-else?

The conditional operator (or Ternary operator) is an alternative for 'if else statement'.

Is switch statement alternative to IF 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.

Which is faster switch or if-else?

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.

Why is switch better than if-else?

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.


1 Answers

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()
  );
}
like image 82
4 revs Avatar answered Oct 11 '22 03:10

4 revs