Both codes have behavior that throws an exception if the value doesn't exist.
Optional<FreePosts> byId = Optional.ofNullable(freePostsRepository.findById(id))
.orElseThrow(NoSuchElementException::new);
FreePosts byId = freePostsRepository.findById(id)
.orElseThrow(NoSuchElementException::new);
I would like to know the difference between the two codes.
CodePudding user response:
Both codes have behavior that throws an exception if the value doesn't exist.
In fact, that is not true. They don't both behave that way.
One of those two versions is incorrect, but which one it is depends on the declared return type of findById
is.
If the return type is
FreePosts
, then the second version does not compile, and it is therefore incorrect.The first version is equivalent to this:
FreePosts byId = freePostsRepository.findById(id); if (byId == null) { throw new NoSuchElementException(); }
In my opinion, it would be better to write an explicit throw in this case, not least because you can include a message.
If the return type
Optional<FreePost>
then the second version is correct1.In this case, the first version is going to throw an exception if and only if
findById
returns anull
. But iffindById
is written correctly, it won't ever returnnull
. (Instead, if should return an emptyOptional<FreePosts>
instance.) So:If
findById
doesn't have a bug that causes it to returnnull
, the first version is not going to throw aNoSuchElementException
, and therefore theofNullable(...)
and theorElseThrow(...)
are pointless.If there is a bug in
findById
that causes it to returnnull
, throwingNoSuchElementException
is obscuring the bug.
In conclusion the first version is incorrect.
1 - I guess it is possible that the designer of the repository API has specified that Optional<FreePosts> findById(...)
should return a null
value instead of an Optional
. But that would be a huge mistake, IMO.
CodePudding user response:
To write the first version correctly, I need to null check from findById. Is my understanding correct?