[squid:S1481] Unused local variable false positive

SonarQube: Version 6.7.4 (build 38452)
SonarJavaLanguages: 5.8 (build 15699)
Checkstyle: 4.11
Findbugs: 3.8.0

import java.util.function.BinaryOperator;

public class ValidationChainBuilder<I> {

    private BinaryOperator<Validator<I>> combineValidators() {
        return (validator1, validator2) -> input -> {
            ValidationResult validationResult = validator1.apply(input);
            if (validationResult.isValid()) {
                return validator2.apply(input);
            } else {
                return validationResult;
            }
        };
    }
}

I get this issue Unused local variables should be removed

1 Like

Which variable is unused?

validationResult at line

ValidationResult validationResult = validator1.apply(input);

but it is obviously used below at both the if check and the else branch.

Hello @AndreiPetcu,

Thanks a lot for letting us know about the issue and the very concise code snippet (much appreciated). This is indeed an obvious FP that we need to address. I created the following JIRA ticket to handle it: SONARJAVA-2958

Note that to make your report even better, you could have made it self-contained. Here, I had to rework your example a bit, as I had no idea what could be classes Validator and ValidationResult … which may imply a missing bytecode issue. It’s usually easier for us to get straight to the point in our investigation if we don’t have to deal with unknown dependencies. For instance, in your case the following code sample reproduce the same issue, without any dependencies outside the JDK (and therefore invalidating the lack of bytecode case):

import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;

class A {

  public BinaryOperator<UnaryOperator<Object>> foo() {
    return (a, b) -> input -> {
      Object o = a.apply(input); // FP: 'o' is used 2 times in the lambda
      o.toString();
      return o;
    };
  }
}

Cheers,
Michael

(And thanks @agabrys for the precision question :+1: )

2 Likes

@Michael - I have the same issue within lambda expressions in spring integration code. I’ll assume the issue is more general purpose “lambda” as your code example shows. I mention this in case I can help test a future solution and this is a PITA for a lot of code. :slight_smile: