Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Switch (Case) always wrong?

Are there instances where switch(case) is is a good design choice (except for simplicity) over strategy or similar patterns...

like image 386
StackUnderflow Avatar asked Dec 03 '08 01:12

StackUnderflow


4 Answers

First of all, Simplicity often is a good design choice.

I never understood this bias against switch/case. Yes, it can be abused, but that, so can just about every other programming construct.

Switching on a type is usually wrong and probably should be replaced by polymorphism. Switching on other things is usually OK.

like image 51
James Curran Avatar answered Oct 26 '22 22:10

James Curran


Use Switches when you're testing on values of primitives. (ie. integers or characters).

Use polymorphism when you are choosing between different types.

Examples : Testing whether a character the user has entered is one of 'a', 'b' or 'c' is a job for a switch.

Testing whether the object you're dealing with is a Dog or Cat is a job for polymorphic dispatch.

In many languages, if you have more complicated values you may not be able to use Switch anyway.

like image 32
3 revs Avatar answered Oct 26 '22 22:10

3 revs


For one, readability.

like image 5
John T Avatar answered Oct 26 '22 23:10

John T


Yes, definitely. Many times your switch is only relevant to a very small part of your overall logic and it would be a mistake to create whole new classes just for this minor effect.

For example, let's say you have a database of words, the user input another word, and you want to find that word in the database but include possible plurals. You might write something like (C++)


vector<string> possible_forms;
possible_forms.push_back(word);
char last_letter = word[word.size() - 1];
switch (last_letter) {
  case 's':
  case 'i':
  case 'z':
    possible_forms.push_back(word + "es");
    break;
  case 'y':
    possible_forms.push_back(word.substr(0, word.size() - 1) + "ies");
    break;
  default:
    possible_forms.push_back(word + "s");
}

Doing this with strategies would be overkill.

like image 5
lacker Avatar answered Oct 27 '22 00:10

lacker