0

I setup a javax.xml.bind.ValidationEventHandler which listens for xml validation errors when unmarshalling an xml document.

Is there really a need to check if the List of errors isEmpty()?

Or should I remove it and just have the for loop?

I'm not sure if the for loop is any way more expensive than a simple if statement.

T instance = (T) unmarshaller.unmarshal(..);
        
if (!eventHandler.getErrors().isEmpty()) {
  for (XSDValidationEventHandler.Error error : eventHandler.getErrors()) {
    // extract error, and log it
  }
}

XSDValidationEventHandler.java, custom ValidationEventHandler implementation:

public class XSDValidationEventHandler implements javax.xml.bind.ValidationEventHandler {

  private List<Error> errors = new ArrayList<Error>();

  @Override
  public boolean handleEvent(ValidationEvent event) {
    final Error error = new Error(event.getLocator().getLineNumber(), event.getMessage());
    errors.add(error);
    return true;
  }

  ..

  public class Error {

    private int lineNumber;
    private String message;
    public Error(int lineNumber, String message) {
      this.lineNumber = lineNumber;
      this.message = message;
    }
  }
}
1
  • 2
    As a note, don't name classes things that conflict with java.lang, such as Error. Commented Jul 28, 2021 at 21:48

2 Answers 2

4

You don't need it in that particular scenario because the enhanced for loop won't do anything if is empty.

For other situations it might be needed, but I think that's extremely premature optimization, checking if for a boolean to be true or false is almost negligible.

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

Comments

0

You don't need to check the list is empty before starting the loop.

It ignore when the list size is zero. In this case, you need to check null for the list to prevent NullPointerException.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.