False positives for squid:S3655 Optional value should only be accessed after calling isPresent()

752 views
Skip to first unread message

david...@gmail.com

unread,
Aug 31, 2017, 3:17:56 PM8/31/17
to SonarQube
Hi,

the Java rule squid:S3655 is triggered even if isPresent() is called but that Optional instance is first retrieved from another object, e.g cases like this are falsely reported:

if (x.getY().isPresent()) {

    doSomething(x.getY().get());

}

 

(getY is a simple getter for attribute y of type Optional in x)

Since this pattern is quite common, I need to disable this rule until it is fixed. Thank You.

Michael Gumowski

unread,
Sep 1, 2017, 12:04:41 PM9/1/17
to david...@gmail.com, SonarQube
Hello David,

You are hitting here a known limitation (feature?) of our symbolic execution (SE) engine. We can not guarantee (due to parallelism, notably [1]) that the value of the Optional field in x has not changed between two calls to getY(). 
With cross-file analysis (currently as an experimental phase), we should be able to tell that the method is always returning the same object, and therefore be able to somehow keep the state of the field. Nevertheless, it will still not prevent it to change in case of parallelism. Note that there is no immediate work planned on following state of fields. 

Consequently, to me, these issues are not FPs, and your only solution to not raise them is to use an intermediary variable, being the result of "x.getY()". It will also be the guarantee that the Optional is present as well after checking it. I would find it a better solution than disabling the rule, but if you are using this pattern everywhere, it can indeed be costly to fix.

As a side note: you may want to reconsider using Optional as class fields. As far as I can tell, it goes against Java designers recommendations regarding usages of Optionals. You may want to have a look here:
Cheers,
Michael

[1] : Extrapolating if we are, or not, in a parallelized environment is a tricky subject that we don't plan to address for the time being

--
You received this message because you are subscribed to the Google Groups "SonarQube" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sonarqube+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sonarqube/b54a3712-60f5-4a93-b31c-d745e64f5013%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Michael Gumowski | SonarSource
Software Developer, Language Team
http://sonarsource.com
Reply all
Reply to author
Forward
0 new messages