0

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.

Josh
  • 121
  • 1
  • 14
  • Maybe this might help for multiple fields: https://stackoverflow.com/a/31582740/1605834 – log N May 10 '22 at 15:01
  • Have you seen this [guide](https://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced002.htm)? Also [this answer](https://stackoverflow.com/a/23133086/4934937) may already help you. – maio290 May 10 '22 at 15:07
  • Also, ‘Optional.of‘ ist the wrong choice die nullable rederences. This Methode throws NPE in case of null. – Hulk May 10 '22 at 15:11
  • 2
    While you've noted the example you provided using `Optional` doesn't cover all your needs, you might not realize that `Optional.ofNullable(x).ifPresent(obj -> { ... })` is considered an "abstruse use" of `Optional` by its designer, and doesn't comply with the guidance given in its API notes. Simply use `if (x != null) { ... }` instead. – erickson May 10 '22 at 15:15
  • 2
    I agree with @erickson, the overall problem statement in essence is wrong. Optionals were not designed for validation. "*A typical code smell is, instead of the code using method chaining to handle an Optional returned from some method, it creates an Optional from something that's nullable, in order to chain methods and avoid conditionals.*" - A quote from the [answer by Stuart Marks (JDK developer)](https://stackoverflow.com/a/34458582/17949945) – Alexander Ivanchenko May 10 '22 at 15:30

0 Answers0