Hi all.
I have a interesting code block and an error from SonarLint -
Bug, Major, java:S2259: Null pointers should not be dereferenced.
And here is a method:
public DataType extract(final CloudEvent cloudEvent) {
if (cloudEvent == null) {
LOG.warn("Can't process message because message is null");
return null;
}
if (cloudEvent.getData() == null) {
LOG.warn("Can't process message because data part is not set.");
return null;
}
if (!(cloudEvent.getData() instanceof JsonCloudEventData)) {
LOG.warn("Can't process message because message format is not correct. "
+ "JsonCloudEventData expected and {} received.",
cloudEvent.getData().getClass().getName());
return null;
}
// Rest of logic
}
SonarLint shows the issue here - cloudEvent.getData().getClass().
Method getData() has @Nullable annotation. And, as you can see, there are plenty of checks for null value.
Interesting is when even I rewrite the issued part like this -
You access cloudEvent.getData() several times in this method. SonarLint cannot be sure if the value returned by this method is always the same or changes between calls (could be changed by another thread for example). That’s why the issue is raised.
The easy workaround is to store the value in a local variable, with your last example:
var data = cloudEvent.getData();
message = data != null
? data.getClass().getName()
: "Empty Message";
Thanks for the tip.
You’ve right -there could be a possibility of changing value between calls in multi-threading surface.
This method is called in the rxJava stream, so it should be thread-save, but I don’t think that SonarLint could scan so far.
And yes - your solution is really simple and more elegant then mine -