我想检查我是否在此处使用Optional违反了良好做法。
public Move getChoice() {
Optional<Move> move = Optional.empty();
while (!move.isPresent()) {
System.out.println("Enter move code : R => Rock, P => Paper, S => Scissors");
move = Move.fromMnemonic(consoleReader.readPlayerInput());
}
return move.get();
}
public enum Move
{
ROCK('R'), PAPER('P'), SCISSORS('S');
private final char mnemonic;
public static Move[] values = values();
Move(char mnemonic) {
this.mnemonic = mnemonic;
}
public static Optional<Move> fromMnemonic(char playerInput) {
return Arrays.stream(values).filter(v -> v.mnemonic == playerInput).findFirst();
}
}
我的目标是避免创建另一个Enum'UNKOWN'实例。我读到使用Optional.isPresent和Optional.get是不好的做法。但是我找不到使用Optional.ifPresent或Optinal.map之类的其他功能的方法,因为如果结果无效,我必须循环。
谢谢。
您可以在枚举类型中从char声明为Move的静态Map<Character, Move>
并将其初始化。然后,您可以像这样在fromMnemonic
方法内使用它。
private static final Map<Character, Move> charToMoveMap = Arrays.stream(values)
.collect(Collectors.toMap(Move::getMnemonic, e -> e));
public static Move fromMnemonic(char playerInput) {
return charToMoveMap.get(playerInput);
}
这是您的客户的样子。
public Move getChoice() {
Move move = null;
while (move == null) {
System.out.println("Enter move code : R => Rock, P => Paper, S => Scissors");
move = Move.fromMnemonic('S');
}
return move;
}