javaparsingfilteringvalidating

How to check whether an input conforms to an arbitrary amount of rules in Java?


For my specific task, I'm trying to check whether a word falls into a specified set of part of speech. This could be done like so:

private boolean validate(String word) {
    if (isNoun(word) || isVerb(word) || isParticiple(word) || ... )
        return true;
    else
        return false;
}

However, as you can see it quickly becomes ugly and hard to scale. If I'm testing these strings against a set of 20 rules, there should be a cleaner and more scalable way to do this.

Any thoughts on how I can make my code cleaner and better when scaling?


Solution

  • There sure is. You can construct (or pass in) a List<Predicate<String>>, and then go over it like so:

    // rules being the predicate list
    boolean valid = true;
    for (Predicate<> rule : rules) {
        valid = valid && rule.test(word);
    }
    // At the end of this valid will only remain true if all of the rules pass.