Home > front end >  Using Optionals correctly in service layer of spring boot application
Using Optionals correctly in service layer of spring boot application

Time:05-10

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 ,

  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
public Optional<Questionnaire> getQuestionnaireById(Long questionnaireId) {
    return questionnaireRepository.findById(questionnaireId);
}

CodePudding user response:

I go with way 1 that you have mentioned. In case the object is not present, throw a validation exception or something. This approach also ensures that service layer is in charge of the logic and controller is just used your interacting with the outside world.

CodePudding user response:

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 logic should stay simple and should not contain null checks for optimal readability.

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

@Override
public Questionnaire getQuestionnaireById(Long questionnaireId) {
    Questionnaire questionnaire = questionnaireRepository.findById(questionnaireId)
        .orElseThrow(() -> new QuestionaireNotFoundException(questionnaireId));
    return returnedQuestionnaire;
}
  • Related