jeudi 11 novembre 2021

REST Spring boot validation causing code duplication

I have defined two Spring boot REST resources

POST /customer  

The above resource is for adding a customer with below JSON as request

{ 
 customerFirstName : "John"
 customerLastName : "Doe"
 customerAddress : {
    "addressLine1" : "22 XYZ Drive"
    "addressLine1" : "22 suite"
    "state" : "PY"
    "country" : "Ind"
    "zipCode" : "1235312"
  } 
}

Now I need to implement update the customer info, so a below resource is defined. The requirement is any information related to customer can be updated. So the Input JSON in case of update is same as in case of add request. The only caveat the information that is not provided will not be updated. Only information that is provided will be updated.

PUT /customer/{customerId}

Question : I want to use Spring boot Bean request validation. However the validation requirements are different for add and update resource, so not able to use the same Customer domain model. However the domain model in both cases is exactly same so this is causing a code duplication. How can I avoid that or is it correct to move the validation outside and code.

Example : In case of adding a customer it is mandatory to provide customer address, so one can use annotation like @NotNull . However in case of update customer, the customer address is not mandatory

Aucun commentaire:

Enregistrer un commentaire