I am using Spring boot and analysing my code with sonarqube, on the below line
Optional<Animal> animal = animalRepository.findById(animalId);
if (animal == null) {
throw new DeviceNotValidException("Failed to found animal detail", new String[] { animalId});
}
i am getting this error
Ensure this "Optional" could never be null and remove this null-check. `
As per my understanding, "Optional is generally used as a return type for methods that might not always have a result to return."
I want to make sure that i dont get a null pointer exception even if "findById()" returns null, so i have used "Optional" here.
Is there anything that I can do to improve my code so that the error disappears?
I read this Checking whether an Optional object isn't Empty and null but it did not help.
An optional's application is to reduce null-values.
Checking if the supplied optional is null isn't enough for the compiler to be sure its value isn't.
To check for an Optional's value use either optional.isEmpty();
or optional.isPresent();
.
In your case: check for the repository's response as follows:
Optional<Animal> animal = animalRepository.findById(animalId);
if (animal.isEmpty()) {
throw new DeviceNotValidException("...");
}
Or even simpler:
Animal animal = animalRepository.findById(animalId)
.orElseThrow(() -> new DeviceNotValidException("...");
The last approach ensures animal
not being null.