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

为君一笑 提交于 2020-02-02 16:31:28

问题


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:


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.


来源:https://stackoverflow.com/questions/33985286/how-to-check-whether-an-input-conforms-to-an-arbitrary-amount-of-rules-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!