I am working with code that uses a library i can not change with a method annotated @NotNull (org.jetbrains), that does return null regardless of the annotation. Here is a simplified example:
@NotNull
public Company getCompany(CompanyKey companyKey) {
Company company = em.find(Company.class, companyKey.getKey());
if (company != null) {
return company
} else {
return null;
}
}
To account for getCompany
returning null, the original developer thought he has to check the return value.
Now, reading the docs for @NotNull i see that it says that a NotNull-annotated method will throw an IllegalStateException when it does return null. But i assume that this is only true if the code was compiled in the IDE, because i read somewhere that the Jetbrains compiler inserts this behavior. And production code is usually (and so in this case) not compiled in the IDE.
The null check is no problem to me, but for this code:
Company company = companyService.getCompany(companyKey);
if (company != null) { // <- this is the offending line
// do the intended thing, real code omitted
} else {
log.warning("warning message");
}
i get a warning in the IDE (annoying, but no great problem) and Sonarqube reports this as a bug, because it says that handle it...
is dead code, which is "always buggy and should never be used in production". Now, this is even more annoying and even a real problem, because it reduces the Reliability rating and the code fails to pass the quality gate.
I tried annotating the code like this
@SuppressWarnings("java:S2583") // <- this is the aforementioned Sonarlint rule
Company company = companyService.getCompany(companyKey);
but this does not work because the offending null check is in the following line and the annotation has to be placed on the variable declaration.
I also tried
@Nullable
Company company = companyService.getCompany(companyKey);
which does not have any effect.
I know i could annotate the whole method with @SuppressWarnings("java:S2583")
, but i would like to avoid that and would like to know if there is a better solution.