gpt4 book ai didi

java - 如何处理基于枚举的开关中的默认情况?

转载 作者:行者123 更新时间:2023-12-03 22:14:12 26 4
gpt4 key购买 nike

我有一个枚举,它根据枚举类型评估字符串是否有效。使用开关执行验证。默认操作是这样的:默认:返回 false;

一位程序员添加了一个新类型并忘记更新 isValid(..),导致每次对答案求值时调用 isValid(..) 返回 false .

您认为正确的处理方式是什么?

public enum AnswerType {
TEXT("string"),
INT("integer"),
FLOAT("float");

final String type;

AnswerType(final String type) {
this.type = type;
}

/**
* Checks whether the given answer is valid for this answer type.
* @param answer The provided answer.
* @return true if the answer is valid; false otherwise.
*/
public boolean isValid(final String answer) {

switch (this) {
case TEXT:
return !StringUtils.isEmpty(answer);

case INT:
return NumberUtils.isDigits(answer);

case FLOAT:
return NumberUtils.isNumber(answer);

default:
return false; // Not sure this is best practise.
}
}
}

最佳答案

这是一个奇怪的设计(并且您的代码无法按原样达到默认情况)...为什么不将方法放入每个枚举常量中呢?

public static enum AnswerType {
TEXT("string") {
public boolean isValid(String answer) { return !StringUtils.isEmpty(answer); }
},
INT("integer") {
public boolean isValid(String answer) { return NumberUtils.isDigits(answer); }
},
FLOAT("float") {
public boolean isValid(String answer) { return NumberUtils.isNumber(answer); }
};

private final String type;

AnswerType(final String type) {
this.type = type;
}

/**
* Checks whether the given answer is valid for this answer type.
*
* @param answer The provided answer.
*
* @return true if the answer is valid; false otherwise.
*/
public abstract boolean isValid(final String answer);
}

或者,如果您使用 Java 8,则可以进一步简化代码:

public static enum AnswerType {
TEXT("string", s -> !StringUtils.isEmpty(s)),
INT("integer", NumberUtils::isDigits),
FLOAT("float", NumberUtils::isNumber);

private final String type;
private final Predicate<String> isValid;

AnswerType(final String type, Predicate<String> isValid) {
this.type = type;
this.isValid = isValid;
}

/**
* Checks whether the given answer is valid for this answer type.
*
* @param answer The provided answer.
*
* @return true if the answer is valid; false otherwise.
*/
public boolean isValid(final String answer) {
return isValid.test(answer);
}
}

关于java - 如何处理基于枚举的开关中的默认情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29299317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com