DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
mnivoliez profile image
mnivoliez • Edited

Syntactically, a switch statement express that you work with a limited set of option and only those.

For example, let say you have a mammal and you need to make a specific treatment depending if it's a cat, dog or a bird person (yes bird person are mammal laying eggs, just like the platypus).

As you got a limited set of supported mammals, I'll go for the switch as it is the syntax to express that you handle only that set.

match mammal {
  "dog" => pet_dog(),
  "cat" => judge_cat(),
  "bird_person" => make_dick_move()
}

In comparison, the "trick" with dictionary is making a structure wearing the meaning of a syntax element. I will not advocate against it nor will I support it. It may have some use but bear in mind the "semantic" trade off you are making.

It could be interesting to see if the switch statement is more efficient than a if else (and honestly it depends on so many option that I'm not even sure it will be relevant) but at the very least it tells other programmers "here we work only with those possibilities and only them".