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.
@Override public Questionnaire getQuestionnaireById(Long questionnaireId) { Questionnaire returnedQuestionnaire = null; Optional<Questionnaire> questionnaireOptional = questionnaireRepository.findById(questionnaireId); if(questionnaireOptional.isPresent()) { returnedQuestionnaire = questionnaireOptional.get(); } return returnedQuestionnaire; }
My question is ,
- 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
public Optional<Questionnaire> getQuestionnaireById(Long questionnaireId) { return questionnaireRepository.findById(questionnaireId); }
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:
public interface TodoBoardRepository { Optional<Questionnaire> findByQuestionnaireId(String questionnaireId); // ... }
In service:
@Service @RequiredArgsConstructor // Or generate constructor if you're not using Lombok public class QuestionnaireService { private final QuestionnaireRepository questionnaireRepository; // ... public Questionnaire getQuestionnaireById(Long questionnaireId) { Questionnaire questionnaire = questionnaireRepository.findById(questionnaireId) .orElseThrow(() -> new QuestionaireNotFoundException(questionnaireId)); // Do whatever you want to do with the Questionnaire... return questionnaire; } }