- Укажите подробную информацию о своей цели:
- Покажите код:
У меня есть очень простой фрагмент кода, который выглядит так:Я хочу провести рефакторинг с использованием случая переключения:Код: Выделить всё
public String question(String sentence) { if (sentence.contains("eat")) { return getFoodFromSentence(sentence); } else if (sentence.contains("drink")) { return getBeverageFromSentence(sentence); } else if (sentence.contains("drive")) { return getVehicleFromSentence(sentence); } else if (sentence.contains("travel")) { return getDestinationFromSentence(sentence); [... many many other else if ...] } else { return "sentence with unknown verb"; } } private String getDestinationFromSentence(String sentence) { return ""; //some complex code to extract some info from the sentence } private String getVehicleFromSentence(String sentence) { return ""; //some complex code to extract some info from the sentence } [... all the other actual handling methods ]
- Опишите, что я пробовал:
Код: Выделить всё
public String question(String sentence) {
switch (???) { //issue here, I am not able to come up with the expression
case (sentence.contains("eat")): // issue here, I am not able to have the cases representing the if
return getFoodFromSentence(sentence);
case (sentence.contains("drink")):
return getBeverageFromSentence(sentence);
case (sentence.contains("drive")):
return getVehicleFromSentence(sentence);
case (sentence.contains("travel")):
return getDestinationFromSentence(sentence);
[ ... the other case conditions ... ]
default:
return "sentence with unknown verb";
}
}
Код: Выделить всё
public String question(String sentence) {
Map
, Function> map =
Map.of(s -> s.contains("eat"), s -> getFoodFromSentence(s),
s -> s.contains("drink"), s -> getBeverageFromSentence(s),
s -> s.contains("drive"), s -> getVehicleFromSentence(s),
s -> s.contains("travel"), s -> getDestinationFromSentence(s));
return map.get(???).apply(sentence); // issue here, how to get the correct key of the map?
}
- Вопрос:
Или, может быть, как разрешить карту?
Есть ли другой метод рефакторинга этого if-else-if string.contains(" X")?
Подробнее здесь: https://stackoverflow.com/questions/787 ... -or-better