Is Switch (Case) always wrong?

后端 未结 8 844
情歌与酒
情歌与酒 2020-12-19 00:37

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

8条回答
  •  孤城傲影
    2020-12-19 00:48

    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 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.

提交回复
热议问题