Hacker News new | ask | show | jobs
by lucideer 2183 days ago
Taking this question from the opposite angle, what benefits do switch statements give us over if...elif?

Not actually a heavy Python user, but even though most languages I use regularly are more switch/case-heavy, I've never quite grasped why there's two largely interchangeable ways to do the one thing.

5 comments

In lower level languages, when you use switch, you make it easier for the compiler to generate a jump table.

In higher level langues with strong, static types, the switch statement can indicate to the compiler you want to match on the type of the variable; it can do analysis then to make sure your pattern match is exhaustive.

These are good examples. Especially for a lower level languages this makes a lot of sense.

For higher level languages, I would imagine typeguards would provide some of the desired functionality here, while being much more lightweight than a full alternative conditional syntax.

Specifically to Ruby (therefore, this is not a generic answer), switch/case has syntax for "short form" expressions, that make the conditionals very coincise, by requiring only the variable part of what would otherwise be, repeating whole expressions.

Making an example is simpler than formulating a defition :-):

  case instance
  when MyClass...
  when MyOtherClass...
  ...
  end
which would otherwise be:

  if instance.is_a?(MyClass)
    ...
  elif instance.is_a?(MyOtherClass)
    ...
  ...
  end
if you consider that this has support for many other expressions (regular expressions, ranges...), you'll see a very coincise construct for the purpose.
Switch might "just" be a special case (har har) of if/elif, but it's a significant one: where you're branching only on the value of one variable, and branching on equality. I'd say it's significant enough to merit some special syntax.

To put it another way: when you're branching on the value of a single variable by comparing it to an enumerated set of values, the obvious way to do so is with switch/case.

> what benefits do switch statements give us over if...elif?

Clarity of intent, much as comprehensions provide over imperative loops (even though switch is still imperative in most langauges). Though whether it's enough benefit to be warranted is another question; I think basic switch is not clearly compelling, though adding even basic smarter matching (like Ruby has long had, for instance) makes it moreso.

Having both switch and if/elif allows writing code with less redundancy in it (unnecessary keywords and variables can be elided by choosing one selection construct over the other).
When you say "less redundancy", do you just mean terser code? Or what exactly?

I don't see any DRY trade-offs, unless you're talking on a really micro character-count / code-golf level.