The Apache Thrift code generator generates classes that look something like this. The numCpus
field is nullable, but since it's held as a value type there's another isSet
field to determine if it's really set:
public class TaskConfig extends TBase<TaskConfig, TaskConfig._Fields> {
private boolean isSetNumCpus; // Actual implemntation is a bitfield.
private double numCpus;
public boolean isSetNumCpus() {
return isSetNumCpus;
}
public double getNumCpus() {
return numCpus;
}
public void setNumCpus(double numCpus) {
this.numCpus = numCpus;
this.isSetNumCpus = true;
}
// hashCode, equals, copy constructor, field enum etc. omitted
}
Our style guide prefers wrapping nullable values as Optional so that we can't forget a null check. So it's common to see this bit of code:
TaskConfig task = getTaskConfigFromWire();
Optional<Double> numCpus = Optional.ofNullable(task.getNumCpus());
But this is wrong - thanks to autoboxing this argument can never be null
, and the correct call should look like:
TaskConfig task = getTaskConfigFromWire();
Optional<Double> numCpus = task.isSetNumCpus()
? Optional.of(task.getNumCpus())
: Optional.<Double>empty();
Is there a way to write a PMD rule that catches this call (Optional.ofNullable
called with a value type that will be autoboxed)?