[英]constructing map of if statements
我一直在考慮一種更簡潔的方法來表示 if 語句的組合。 例如,下面代碼描述的情況可能會以某種方式組合。 我當然可以寫出所有這些組合,但這會導致犧牲代碼的可讀性以求詳盡無遺。
if (foo == null) {
System.out.println("Null input");
return 1;
}
if (foo.isEmpty()){
System.out.println("Missing input");
return 2;
}
if (Character.isWhitespace(foo.charAt(0)) || Character.isWhitespace(foo.charAt(foo.length() - 1))){
System.out.println("var cannot begin or end with spaces");
return 3;
}
String[] words = foo.split(" ");
if (words.length > 2){
System.out.println("var cannot be more than two words or intermediate whitespaces");
return 4;
}
if (Pattern.compile("[0-9]").matcher(foo).find()){
System.out.println("var cannot contain digits");
return 5;
}
if (foo.split("\\t+").length > 1){
System.out.println("var cannot contain tabs");
return 6;
}
if (this.var.contains(foo)){
System.out.println("var already exists");
return 7;
}
我見過 pythonic 方法,其中每個案例都被壓縮成 map。是否有可行的 java 數據結構或方法可以使下面的代碼更清晰,同時仍然使我能夠表示 if 語句的所有可能組合?
您可以創建一個要檢查的錯誤List
,每個錯誤都有一個要對輸入進行評估的Predicate
和一條錯誤消息。
record ErrorCondition(Predicate<String> condition, String message){}
List<ErrorCondition> errors = List.of(new ErrorCondition(s -> s == null, "Null input"), // or Objects::isNull
new ErrorCondition(String::isEmpty, "Missing input") /* other checks... */);
// ...
int code = 0;
String foo = "";
for (ErrorCondition error: errors) {
++code;
if (error.condition().test(foo)) {
System.out.println(error.message());
return code;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.