Skip to content

False positive: Analyzer warns about charAt usage when comparison is done in helper method #303

@nilvon9wo

Description

@nilvon9wo

Exercise: Hamming
Repository: exercism/java-analyzer

Summary

The analyzer emits a recommendation to use String.charAt or codePointAt even when charAt is already used, as long as the comparison happens inside a helper method referenced via a method reference rather than inline in the stream.

This produces a false positive warning.


Expected Behavior

If the student uses charAt anywhere in the Hamming-distance calculation, the analyzer should not warn about missing charAt usage.

The following solution should not trigger the recommendation:

import java.util.Objects;
import java.util.stream.IntStream;

public class Hamming {
    private final int length;
    private final String leftStrand;
    private final String rightStrand;

    public Hamming(String leftStrand, String rightStrand) {
        this.leftStrand = Objects.requireNonNull(leftStrand);
        this.rightStrand = Objects.requireNonNull(rightStrand);

        if (leftStrand.length() != rightStrand.length()) {
            throw new IllegalArgumentException("strands must be of equal length");
        }

        this.length = leftStrand.length();
    }

    public int getHammingDistance() {
        return IntStream.range(0, length)
                        .map(this::doesLetterMatch)
                        .sum();
    }

    private int doesLetterMatch(int i) {
        return leftStrand.charAt(i) == rightStrand.charAt(i) ? 0 : 1;
    }
}

This implementation uses charAt exactly as recommended.


Actual Behavior

The analyzer produces this message:

“When comparing characters to calculate the Hamming distance, use the String's charAt or codePointAt method. Other alternatives generally require additional storage…”

This occurs because the analyzer checks only for inline charAt usage inside the stream’s map lambda, not inside a helper method invoked via a method reference.


Suggested Fix

Enhance the analyzer’s pattern detection to recognize charAt usage even when it appears in:

  • helper methods referenced via map(this::methodName)
  • any method involved in the Hamming-distance calculation, not just inline lambdas

This will prevent incorrect warnings and reduce confusion for students using idiomatic stream decomposition.


Additional Notes

  • The submitted solution passes all tests and follows Exercism’s recommended pattern.
  • The current warning may mislead students into thinking their correct approach is wrong.
  • Improving the detection logic would increase clarity and accuracy.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions