The return value of "orElseThrow" must be used
Asked Answered
C

2

29

When I am scanning code with sonar lint the following code shows the bug as "The return value of "orElseThrow" must be used"

itemList.stream()
    .filter(item -> orderItemId.equals(item.getId()))
    .findAny()
    .orElseThrow(() -> new BadRequestException("12345","Item Not Found"));

This is just for a validation purpose no need to return anything from this statement. need to validate whether the item exists or not.

FYI: Eclipse showing a quick fix as squid:S2201

Anybody have any idea how to resolve this bug?

Chastise answered 28/3, 2018 at 10:43 Comment(1)
Thank you @ Aominè for the solution. <code> if(itemList.stream().noneMatch(i->orderItemId.equals(i.getId()))){ throw new BadRequestException("12345","Item Not Found"); }Chastise
C
23

I'm assuming this is a warning (not using the value returned by orElseThrow() shouldn't be an error).

If you wish to eliminate that warning, use isPresent() instead:

if (!itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent()) {
    throw new BadRequestException("12345","Item Not Found");
}

or just avoid using Optionals, and use anyMatch() instead:

if (!itemList.stream().anyMatch(i->orderItemId.equals(i.getId()))) {
    throw new BadRequestException("12345","Item Not Found");
}
Colored answered 28/3, 2018 at 10:47 Comment(5)
Using empty() seems not the correct way.How ever the second option anyMatch() is the perfect solution for this.Thank you.Chastise
for the first solution, I believe you're looking for !itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent() but the better solution would be to use itemList.stream().noneMatch(i->orderItemId.equals(i.getId()))Mulct
@Aominè yep, for some reason I was sure there was an empty() method that indicates whether an existing Optional is empty.Colored
…and eliminate the logical not by using noneMatch in the first place.Durante
My opinion is that this is not a solution changing your code with a simply orElseThrow to something else only because a false positive warning.Longley
D
2

This is a limitation of the sonar, there is an open ticket to resolve this issue (https://community.sonarsource.com/t/fp-java-s2201-optional-orelsethrow-return-value-must-be-used/85204), the best thing to do until it is resolved is to just ignore this rule

Dalston answered 1/11, 2023 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.