-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());
  }
}
2
  • You could make them use the same method signatures. Commented Feb 12, 2018 at 22:58
  • What is BatchValidator? Is this an interface? Does it give a required signature of the validate() method? Commented Feb 12, 2018 at 23:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.