假设您要测试输入是否是几个常量字符串之一,并且忽略性能,它是否是一种反模式:
if ("yes oui ja da".contains(answer)) {
// answer was in the affirmative
}
而不是更传统的:
private static List<String> affirmativeAnswers = Arrays.asList("yes", "oui", "ja", "da");
if (affirmativeAnswers.contains(answer)) {
// answer was in the affirmative
}
它的代码少了很多,也更容易阅读,但它是“黑客”吗?
编辑:
为了更安全,如果您担心部分匹配,您可以将其编码为:
if (",yes,oui,ja,da,".contains(',' + answer + ','))
它的代码仍然少得多(尽管变得丑陋)