0

I don't understand why the switch or equivalent is so popular in languages. To me, it seems like it had a place back in the days when the alternative was lots of nested if statements in the else part of other if statements. Now that we have else if, why do we need it?

If we take the following:

switch (expr) {
  case "Oranges":
    document.write("Oranges are $0.59 a pound.<br>");
    break;
  case "Apples":
    document.write("Apples are $0.32 a pound.<br>");
    break;
  case "Bananas":
    document.write("Bananas are $0.48 a pound.<br>");
    break;
  default:
    document.write("Sorry, we are out of " + expr + ".<br>");
}

It is clearly more readable than below?

if (expr == "Oranges") {
    document.write("Oranges are $0.59 a pound.<br>");
} else {
    if (expr == "Apples") {
        document.write("Apples are $0.32 a pound.<br>");
    } else {
        if (expr == "Bananas") {
            document.write("Bananas are $0.48 a pound.<br>");
        } else {
            document.write("Sorry, we are out of " + expr + ".<br>");
        }
    }
}

But how is it more readable than:

if (expr == "Oranges") {
    document.write("Oranges are $0.59 a pound.<br>");
} else if (expr == "Apples") {
    document.write("Apples are $0.32 a pound.<br>");
} else if (expr == "Bananas") {
    document.write("Bananas are $0.48 a pound.<br>");
} else {
    document.write("Sorry, we are out of " + expr + ".<br>");
}
gnat
  • 20,543
  • 29
  • 115
  • 306
neelsg
  • 483

1 Answers1

2

Now we have else if

In many language specifications, Java certainly being among them (I'd have to look up Java*script*), else if isn't a thing. You have if (expr) {block} [else statement] where an if statement is itself a statement. I'm not sure there are many languages in which the idea of an "else if" has been impossible.

Switch/case statements originated because they allowed the compiler to create a jump table, allowing one to create a large number of different "paths" without necessarily having to pay for n comparisons. A jump table can save a fair number of instructions, and once that really mattered. You can view a case statement as a goto label even now.

These days the differences are less relevant, but some think that switch/case better shows intent.

Personally I'm more inclined to agree with your conclusion, that it isn't necessarily any more readable and introduces conceptual wobbles with a case label being logically a "block" but not actually scoped as one.

Phoshi
  • 1,633