Проблема с рефакторингом if-else-if string.contains("X") для переключения регистра (или лучше)JAVA

Программисты JAVA общаются здесь
Anonymous
Проблема с рефакторингом if-else-if string.contains("X") для переключения регистра (или лучше)

Сообщение Anonymous »

  • Укажите подробную информацию о своей цели:
Я хотел бы провести рефакторинг if-else-if string.contains(" X") в Java для переключения регистра или карты.
  • Покажите код:

    У меня есть очень простой фрагмент кода, который выглядит так:

    Код: Выделить всё

         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

Вернуться в «JAVA»