Skip to content
Advertisement

Using Optionals correctly in service layer of spring boot application

I new to spring boot application development. I using service layer in my application, but came across the repository method that return Optional as shown below.

JavaScript

My question is ,

  1. whether I am using the Optional correctly here. And is it ok to check this optional (isPresent()) in the RestController and throughing exception is not present.Like below
JavaScript

Advertisement

Answer

I wouldn’t go for either option tbh, especially not the first. You don’t want to introduce null values inside your domain. Your domain should stay as simple as possible, readable and void of clutter like null checks.

You might want to read through the optional API for all your options, but personally I would go for something like this:

In repository:

JavaScript

In service:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement