-1

How do I avoid using instanceof and casting in this situation if I want to have different validators where the method signatures differ?

Code

for(BatchValidator validator : validators) {
  try {     
    if (validator instanceof BatchErrorValidator) {
      ((BatchErrorValidator<T>) validator).validate(targets);
    } else if (validator instanceof BatchWarningValidator) {
      ((BatchWarningValidator<T>) validator).validate(targets, header);
    }
  } catch (BatchValidationException e) {
    handleImportExceptions(e, header.getSequenceId());
  }
}
A_B
  • 1,009
  • 3
  • 15
  • 37

1 Answers1

5

Why not make BatchValidator.validate() take 2 args: targets and headers. The individual implementations can decide which of the args they need to use.

This way your calling loop just passes the same parameters to each validator and you don't need instanceof or any casting.

John3136
  • 28,809
  • 4
  • 51
  • 69