Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive: Redundant nullcheck #160

Closed
willhains opened this issue Jun 12, 2017 · 5 comments
Closed

False positive: Redundant nullcheck #160

willhains opened this issue Jun 12, 2017 · 5 comments

Comments

@willhains
Copy link

I have a generic type as follows, which calls .toString() on an instance of the parameter type.

public final class Simple<T>
{
  private final @Nonnull T _raw;
  public Simple(@Nonnull T raw) { _raw = raw; }
  public @Nonnull String toString()
  {
    final String string = _raw.toString();
    return string == null ? "" : string;
  }
}

FindBugs gives a RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE warning on the null check of string, saying that it is "a known non-null value". However, this can be trivially show to be incorrect, as the following code demonstrates.

class Naughty
{
  public String toString() { return null; }
  public static void main(String... args)
  {
    final Simple<Naughty> simplyNaughty = new Simple<>(new Naughty());
    System.out.println(simplyNaughty.toString().length());
  }
}

If Simple.toString() did not have the null check on string, and return an alternate non-null value, then we would get an NPE thrown when calling .length(). Since _raw is of the unknown type T, FindBugs should not treat _raw.toString() as "a known non-null value".

@iloveeclipse
Copy link
Member

toSting() should never return null.

@castocolina
Copy link

castocolina commented Jul 30, 2018

@iloveeclipse , you asume any third-party API class method dont return null

@iloveeclipse
Copy link
Member

Yes, I assume that no one in the world should ever return null from toString(), because not doing so would violate the contract of Object.toString().

@castocolina
Copy link

But this rule is applicable for every variable, not only the return of toString(). This assumption fails my code every time when check variables depends on third-party API methods. My you what to add rules for null return in toString :-p

@iloveeclipse
Copy link
Member

Please note, that this project is dead. If you want to contribute something, please do it via https://github.com/spotbugs/spotbugs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants