I'm using Optional parameters for my Rest controller, in my case to distinguish which method to call:
@GetMapping("/cars")
@ResponseBody
public List<CarsDTO> getAllCarsByCat(@RequestParam Optional<Integer> cat1,
@RequestParam Optional<Integer> cat2) {
if (cat1.isPresent() && cat2.isPresent())
return carsService.getAllCarsByCat1AndCat2(cat1.get(), cat2.get());
else if (cat1.isPresent())
return carsService.getAllCarsByCat1(cat1.get());
else if (cat2.isPresent())
return carsService.getAllCarsByCat2(cat2.get());
else
return carsService.getAllCars();
}
Why does the highest voted response of the thread below propose that "Using Optional parameters causing conditional logic inside the methods is literally contra-productive."?
Why should Java 8's Optional not be used in arguments
I do exactly that and consider it as the most readable and straight forward solution. What is bad with this approach?