jeudi 26 décembre 2019

Validate when fields depend on one another

I am passing a request object name Person to controller. Lets say the object has 2 two fields. The following business rule apply:

  • If field age has a value < 18, the field sin should be left blank;
  • If not, it will produce exception with message the sin should be blank with age < 18 or another way is to set the field sin to empty string("").

What is the best way for me to validate those inputs when they depend on each other. My way to deal with them is to validate them inside the controller method. So it should look something like that

@GetMapping("/..."
public ResponseEntity<PersonResponse> getPersonResult(GetPersonRequest request)
{
    if (request.getAge() < 18)
    {
        if (request.getSin.length > 0)
            request.setSin("") 
    }
    PersonResponse response = callThirdPartyAPIToRetrieveInformationAboutThatPerson(request)
    return response ;
}

Is there any more elegant way to code ? Is it ok for the controller method to contain any validation logic like that ? am i violating the Single Responsibility in SOLID design ?

Aucun commentaire:

Enregistrer un commentaire