I run SonarQube to check my code and I found a case which I don't understand the reported error.
My code is:
private static final int BASE_ID = 100_000_000;
private boolean isValidId(Id id) {
return id.asInteger().isPresent() && id.asInteger().get() >= BASE_ID;
}
The method asInteger
returns Optional<Integer>
The error that I am getting from sonarqube is
Call "Optional#isPresent()" before accessing the value.
in the return line.
I understand that the code is ok as the second part of the if
won’t get executed if the first one is false. I know that this can be solved with a .filter(..).isPresent()
but I like it more this way.
Any ideas why would this happen?
Optional of() method in Java with examples Parameters: This method accepts value as parameter of type T to create an Optional instance with this value. Return value: This method returns an instance of this Optional class with the specified value of the specified type.
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
So, to overcome this, Java 8 has introduced a new class Optional in java. util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run.
The Optional class in Java is a container that can hold, at max, one value and gracefully deals with null values. The class was introduced in the java. util package to remove the need for multiple null checks to protect against the dreaded NullPointerExceptions during run-time.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With