vendredi 29 octobre 2021

Check for Null values without IF statements

I have the following method that gets multiple optional values as parameters.

@GetMapping(path = "/search", produces = {MediaType.APPLICATION_JSON_VALUE , MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<String> getCategoriesByExample(
        @RequestParam(required = false) String id,
        @RequestParam(required = false) String name,
...
){

The problem is, since all the parameters are optional, when I assign them in a object I need to check all of them for nullability in such a way that multiple IF's are necessary. If I don't, the program throws an error for assigning the variable a null value.

Category cat = new Category();
    
    if (id!=null) 
        cat.setId(UUID.fromString(id));
    
    if (name!=null) 
        cat.setName(name);
...

So is there a way for me to to check all of then without using the if statement?

Aucun commentaire:

Enregistrer un commentaire