Squid:S3655 is not fired

java
sonarqube
rules

(Alexander) #1

We’re using SonarQube Version 6.7.5 (build 38563).

Squid:S3655 is not fired for the following line:
‘’‘Field fld = this.getFields().stream().filter(field -> field.getName().equals(“fieldname”)).findFirst().get();’’’

Isn’t isPresent() needed in this case?


(Tibor Blenessy) #2

Hello @alex5kov ,

normally the issue should be raised in this case. However it is possible, that the analyzer was not able to infer return value of findFirst() invocation and was unable to detect this. Are you providing all dependencies for the analysis? Are you able to create small example reproducing your issue?


(Richard Lindner) #3

Hi Tibor,

this issue came up when we analyzed a big project. I cannot build a small reproducible variant of the problem for you. I mean we originally felt this may be just some mis-configuration on our part, because the problem was flagged in some parts of our code, but not in others.

The actual check seems pretty straightforward to me. When you see a findFirst() follow it to where the Optional is resolved and see if a check is done beforehand. I can give you the actual code snippet if that helps…

    class Info {
    /**
     * Constructor.
     *
     * @param object           the object about to be serialized
     * @param serializedFields collection of fields to be serialized
     * @param jsonView         the target serialization view class (JsonView annotation)
     */
    public Info(Object object, Collection<Field> serializedFields, Class<?> jsonView) {
        this.object = object;
        this.fields = Collections.unmodifiableCollection(serializedFields);
        this.jsonView = jsonView;
    }

    public Field getFieldByName(String fieldName) {
        return this.getFields().stream().filter(field -> field.getName().equals(fieldName)).findFirst().get();
    }

    @Getter
    Object object;

    @Getter
    Collection<Field> fields;

    @Getter
    Class<?> jsonView;
}

(Tibor Blenessy) #4

Hello,

the rule is able to detect findFirst().get() invocation (see the unit test here for example). The reason why it doesn’t work in your case is that you are using Lombok annotation to generate the getter, so the analyzer is not able to “see” getFields method and infer it’s return value.

We do not support Lombok, so you will see some false positives and false negatives in such code.


(Richard Lindner) #5

Ahh that makes sense. There are a couple of code-scanners that don’t support Lombok, which is a shame. I feel most parts of Lombok are so useful they should not just be supported, but be part of the language itself.

Thanks for clearing things up.


(Tibor Blenessy) #6

You may try to “delombok” your code for the analysis, but maybe it’s not worth the trouble.

Lombok is already part of the language, it’s called Kotlin :wink: