0

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?

Petrus K.
  • 840
  • 7
  • 27
  • 56
  • Can you clarify what you mean by "cleaner and more scalable"? – cimmanon Nov 29 '15 at 17:10
  • It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Thanks! – Madara's Ghost Nov 29 '15 at 18:20
  • Alright, I'll move my edit to a separate one, thanks. EDIT: moved here: http://stackoverflow.com/questions/33986324/how-to-implement-a-predicate-in-java-used-for-cross-checking-a-string-against-an – Petrus K. Nov 29 '15 at 18:22

1 Answers1

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.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • Thanks for the help! I've been looking at Predicate because I haven't been using it before. Some noteworthy links: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html; http://stackoverflow.com/questions/2955043/predicate-in-java; http://www.java2s.com/Tutorials/Java/java.util.function/Predicate/index.htm I'll paste in my code, as I'm unsure of how to implement Predicate in the context of my code. – Petrus K. Nov 29 '15 at 18:11
  • More specifically, how can I make a list of rules contain references to the support methods that I've implemented. What I want to do essentially is pass a String (word) and have it cross-checked against multiple methods that return true or false, and then logically AND those outputs. – Petrus K. Nov 29 '15 at 18:21