'How to validate request which built from other classes?

There is a class UserRequest

class UserRequest {
  private Name name;
  private Address address;
  private Date dob;
  //getters and setters
}

This class is built from other classes: Name and Address and Date. they might look like

class Name {
 private String first;
 private String second;
 //getters and setters
}

class Address {
 private String street;
 private String state;
 private String zip;
 //getters and setters
}

I need to validate all fields and return a multi-error response.

public List<ErrorItem> validate(UserRequest request){
 List<ErrorItem> errors = new ArrayList<>();

 if(request.getName().getFirst() == null){
  errors.add(new ErrorItem(...))
 }

 if(request.getName().getSecond() == null){
  errors.add(new ErrorItem(...))
 }

 return errors;
}

You can notice possible NPE.

On one side using classes-wrappers above the group of fields that are the same logically is the best practice(Name: first and second, Address: street, state, zip).

On the second side, it brings additional checks/validations. Also, I don't know what should I say to a user if he passed empty UserRequest:

if(request.getName() == null) {
  errors.add(???)//I don't have a message or error code for that.
 }

Should I validate cases such as that? If I should throw an exception - what exception should I throw? IlligalArgumentException? Or maybe, a simple class with all fields in one parent class is better? I don't think so. So, what is best practice?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source