False positives for java:S1854

Assigning to a variable in an if/else for effective-final assignment marks the assignments as an issue under java:S1854 when the variable is then used in a lambda expression.

versions used (SonarQube, Scanner, language analyzer)
IntelliJ plugin: 4.14.2.28348
IntelliJ Idea: 2020.3.3

Here’s a screenshot of the code highlighted
image

Here’s a snippet of the code, the issue seems to occur when the personTypeCrmEntity param is used in a lambda function. The collections you can see are from the Vavr library.

    List<Tuple2<PersonType, CrmEntity>> personTypeCrmEntity;
    if (etlConfig.getCrmEntityMap().containsKey("Lead")) {
      personTypeCrmEntity = List.of(
          Tuple.of(PersonType.CANDIDATE, crmEntityMap.get("Candidate")),
          Tuple.of(PersonType.CLIENT_CONTACT, crmEntityMap.get("ClientContact")),
          Tuple.of(PersonType.LEAD, crmEntityMap.get("Lead"))
      );
    } else {
      personTypeCrmEntity = List.of(
          Tuple.of(PersonType.CANDIDATE, crmEntityMap.get("Candidate")),
          Tuple.of(PersonType.CLIENT_CONTACT, crmEntityMap.get("ClientContact"))
      );
    }
    return new SimpleRowProcessor(
        rows -> processUpsert(rows, connector, personTypeCrmEntity, crmEntityMap, mappedEntities),
        rows -> processDelete(rows, crmEntityMap, mappedEntities));

I can’t share any more of this code but I could perhaps find some time to make an example project/code at some point if people can’t reproduce this issue.

Hello @ChrisLane

This issue typically arises when the project is missing dependencies or the bytecode is incomplete. For example, I manage to reproduce this issue by writing this code:

  void fpWithAssignment(boolean cond) {
    List<String> myList;
    if (cond) {
      myList = List.of("a", "b"); // Issue here
    } else {
      myList = List.of("c", "d"); // Issue here
    }
    new MyClass(str -> bar(str, myList));
  }

  static void bar(String s, List<String> lst) {

  }

MyClass.java

import java.util.function.Consumer;
class MyClass {
  MyClass(Consumer<String> f) {
  }
}

When I just created the files, I have two false positives. MyClass.class is not present under target/.... When I build the project, MyClass.class is present, the issues disappear.

In any way, we should be able to identify this situation, and not report an issue to avoid false positives. Ticket created: SONARJAVA-3797.

Thanks for reporting this issue.
Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.