FP for java:S2583 with conditions involving Micronaut StringUtils.trimToNull

SonarLint 6.5.1.43866 with IntelliJ 2021.3.3 (build #IC-213.7172.25) and SonarQube Developer Edition Version 8.9.6 (build 50800).

package com.example;

import io.micronaut.core.util.StringUtils;

public class SonarLintBug {

  private final String internalValue;

  public SonarLintBug(String value) {
    if (StringUtils.trimToNull(value) == null) { // reports java:S2583 against this condition
      internalValue = "";
    }
    else {
      internalValue = value;
    }
  }
}

SonarLint analysis reports: Change this condition so that it does not always evaluate to “false”, which means SonarLint believes that trimToNull() can never return null.

This is a false positive because the trimToNull() method will return null if the input is blank/empty/null - here’s the source:

    /**
     * Trims the supplied string. If the string is empty or null before or after
     * trimming, null is returned.
     *
     * @param string the string to trim
     * @return the trimmed string or null
     */
    @Nullable
    public static String trimToNull(@Nullable String string) {
        return Optional.ofNullable(string)
                .map(String::trim)
                .filter(StringUtils::isNotEmpty)
                .orElse(null);
    }