Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect autoboxing in a PMD rule?

Tags:

java

pmd

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)?

like image 684
kevints Avatar asked May 20 '15 22:05

kevints


1 Answers

I would download the PMD binary and use the designer, you will be able to see how the expression has a PrimaryExpression and PrimaryPrefix of 'Name: Optional.ofNullable', then you can inspect the PrimarySuffix Arguments to find the method call or variable. You'll then have to look back up the class file to find the types and use that to determine whether you have incorrectly Optionalised an autoboxed value.

I personally would implement this as a Java rule not an XPath one.

See http://pmd.sourceforge.net/pmd-4.3.0/howtowritearule.html for more details

like image 109
SilentICE Avatar answered Nov 03 '22 08:11

SilentICE