[squid:S1481] Unused local variable false positive


(Andrei Petcu) #1

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

(Adam Gabryś) #2

Which variable is unused?

(Andrei Petcu) #3

validationResult at line

ValidationResult validationResult = validator1.apply(input);

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

(Michael Gumowski) #4

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
      return o;


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