Reputation: 2631
I get a following bug from sonarqube
A "NullPointerException" could be thrown; "getFolderPath()" can return null.
for the following line:
if (upstreamContent.getFolderPath() != null && !upstreamContent.getFolderPath().isEmpty()) {
...
}
Where upstreamContent may not be null.
How can I fix it in sonarqube without turning off the rule?
UPDATE:
Someone asked me to show the source of UpstreamContent
public class UpstreamContent {
@Nullable
private String folderPath;
...
@CheckForNull
@Nullable
public String getFolderPath() {
return folderPath;
}
public void setFolderPath(String folderPath) {
this.folderPath = folderPath;
}
}
Upvotes: 3
Views: 15379
Reputation: 1074595
Probably by saving the result to a variable rather than making the call twice:
String path = upstreamContent.getFolderPath();
if (path != null && !path.isEmpty()) {
...
}
Maybe you or I know that if it doesn't return null
the first time, it won't the second (I don't, actually, because I don't know what upstreamContent
is :-) ), but a general-purpose tool can't know or assume that. For all it knows, it could return non-null
the first time and null
the second. By saving the call result to a variable, we ensure that Sonarqube and anyone coming along later to read and maintain the code knows, for sure, that we've done a null
check before calling isEmpty
.
In fact, now that you've posted the code for upstreamContent
's class, it's entirely possible for getFolderPath
to return non-null
for the first call and null
for the second (if another thread calls setFolderPath(null)
in-between).
Upvotes: 11