如何检查输入是否符合Java中任意数量的规则? [英] How to check whether an input conforms to an arbitrary amount of rules in Java?

查看:82
本文介绍了如何检查输入是否符合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;
}

但是,如您所见,它很快变得丑陋且难以扩展. 如果我要按照20条规则对这些字符串进行测试,则应该有一种更干净,更可扩展的方法来实现此目的.

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?

推荐答案

肯定有.您可以构造(或传递)List<Predicate<String>>,然后像下面这样遍历它:

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.

这篇关于如何检查输入是否符合Java中任意数量的规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆