'Using Optionals to Validate Incoming Requests

I have a use case where I am needing to validate incoming requests with a bunch of fields, and if certain ones are null or empty, I want to return a detailed response from my API letting the client know that they need to include a value for that field. I am new to Optionals, and think there may be a more efficient and streamlined way to do this.

I have an incoming request:

public class myRequest {

 private String fieldOne;  
 private String fieldTwo: 
..etc
}

And I have validations in place :

if(StringUtils.isEmpty(request.getFieldOne)){
    return new MyResponse("Please include a field one value")
}else if(StringUtils.isEmpty(request.getFieldTwo)){
    return new MyResponse("Please include a field two value")
}else if(StringUtils.isEmpty(request.getFieldThree){
     //etc..
}

Now I would think i converted the incoming requests to an optional, I would be able to validate these fields more efficiently.

Optional<MyRequest> request = Optional.of(request);
request.ifPresent((req ) ->{
    //checks if the request itself is null...but what about fields, or objects?
});
    

Some of the incoming fields are objects themselves as well. Wondering if anyone has come across this.



Sources

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

Source: Stack Overflow

Solution Source