Calling Optional#isPresent() in single line is reported as not called
Sonarqube cannot guarantee that the two calls to id.asInteger()
returns the same object, e.g. because multi-threading might have changed the value of id
between the two calls, so it is correctly stating that the presence hasn't been adequately tested.
Change code to assign to a local variable first, to ensure that isPresent()
and get()
are called on the same object:
private boolean isValidId(Id id) {
Optional<Integer> idAsInteger = id.asInteger();
return idAsInteger.isPresent() && idAsInteger.get() >= BASE_ID;
}
You can write that as a single statement btw:
return id.asInteger()
.map(x -> x >= BASE_ID)
.orElse(false)
but sonar complaining is because well it's a false positive in this case.