Search code examples
javavalidationjava-8validationrules

Best way to validate an object in java


I'm new to programming. I have a list of objects that I want to validate (not short circuit, but run a list of validation rules by each one).

Initially I had a huge if/else statement but it didn't look very pretty. I think something like this would be better:

foreach (object: objects) {
  foreach (rule: validationRules) {
    try {
      rule.validate(object)
    } catch {
      // Write to log
      // Increment counter for rule
    }
  }
}

I just don't know how to go about creating the validation rules. I'd like to use Java 8 predicates because I hear that's what I should be using, but I'm not sure how to go about doing it. I think I might create an interface with the rules and then an implementation with each rule defined and also the list of rules. Does this sound like a good way to go about solving this problem?

Thanks!


Solution

  • Your for loop is a perfectly good idea.

    The predicate idea depends on whether that's a useful way to do whatever you mean by validation. I generally advise people not to lock themselves into a particular "must use X" way of thinking before starting a problem. Plan to use whatever is simplest and/or most efficient, but focusing on a specific feature leads to a kind of "trying to screw with a hammer" mentality.

    Predicates would not require a loop, but would not, I think, be a good choice for performance, as they would create new collections of objects if you use them to filter, which is a potentially expensive operation. A simple rule that is a method ( as your own sketch shows ) seems simpler, both conceptually and to maintain as code.