简体   繁体   中英

constructing map of if statements

I have been thinking about a cleaner way to represent combinations of if-statements. 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?

You can create a List of errors to check for, each with a Predicate to evaluate on the input and an error message.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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