简体   繁体   English

构建 map 的 if 语句

[英]constructing map of if statements

I have been thinking about a cleaner way to represent combinations of if-statements.我一直在考虑一种更简洁的方法来表示 if 语句的组合。 For example, the cases described by the code below could potentially be combined in some manner.例如,下面代码描述的情况可能会以某种方式组合。 I could certainly write out all of those combinations, but that would result in sacrificing code-readability for exhaustiveness.我当然可以写出所有这些组合,但这会导致牺牲代码的可读性以求详尽无遗。

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;
        }

I have seen pythonic approaches where each case is condensed into a map. Is there a viable java data structure or approach that would make the code below cleaner while still enabling me to represent all possible combinations of if-statements?我见过 pythonic 方法,其中每个案例都被压缩成 map。是否有可行的 java 数据结构或方法可以使下面的代码更清晰,同时仍然使我能够表示 if 语句的所有可能组合?

You can create a List of errors to check for, each with a Predicate to evaluate on the input and an error message.您可以创建一个要检查的错误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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM