Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Optional#isPresent() in single line is reported as not called

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?

like image 274
Pablo Matias Gomez Avatar asked Nov 06 '18 20:11

Pablo Matias Gomez


People also ask

How do you use optional?

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.

What is an optional in coding?

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.

Why is Java optional 8?

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.

What is an optional class?

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.


1 Answers

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;
}
like image 105
Andreas Avatar answered Sep 19 '22 11:09

Andreas