How to check whether an input conforms to an arbit

2019-06-10 14:43发布

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?

1条回答
ら.Afraid
2楼-- · 2019-06-10 15:23

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.
查看更多
登录 后发表回答