1

I am getting "Possible null pointer dereference due to return value of called method" FindBugs error on following line.

Specification spec = Specification.where(idSpec).and(nameSpec)
    .and(typeSpec).and(statusSpec);

Specification is Spring data JPA class. Some of its snippets:

    @Nullable
    static <T> Specification<T> where(@Nullable Specification<T> spec) {
        return spec == null ? (root, query, builder) -> null : spec;
    }

    @Nullable
    default Specification<T> and(@Nullable Specification<T> other) {
        return composed(this, other, (builder, left, rhs) -> builder.and(left, rhs));
    }

Is this valid FindBugs error? How to fix it?

How can I avoid null checks on each and every call of where and and? As such null checks will reduce readbility of code which currently reads just like a query using method chaining.

Smile
  • 3,832
  • 3
  • 25
  • 39

2 Answers2

1

Is this valid FindBugs error?

Yes it is.

How to fix it?

Add the tests for null or tell FindBugs to be quiet.

How can I avoid null checks on each and every call of where and and? As such null checks will reduce readbility of code which currently reads just like a query using method chaining.

There is no magic bullet for this. You need to do one of the following:

  • add the ugly null checks, or
  • code your own replacement1 for Specification where the arguments and results are not Nullable, or
  • individually suppress any potential bugs found by FindBugs that you "know" are not real bugs, or
  • turn that check off completely.

Note that if you suppress a Findbugs check that is an actual bug, you are liable to get NPEs at runtime. So the onus would be on you to use other techniques to find any (real) bugs in your application could lead to NPEs. For example, more comprehensive unit and system tests.


1 - I am not sure if this is technically feasible, but you may be able to write subclasses of Specification and friends, and then change your code to use them instead of the originals. There will be downsides to doing this ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks for the answer. As, @Andy mentioned `where()` will never return null and should not be marked `@Nullable`. I have raised [DATAJPA-1766](https://jira.spring.io/browse/DATAJPA-1766) to get it removed. If Spring team doesn't accept it, I will go ahead with one of the approaches you have suggested. – Smile Aug 07 '20 at 10:55
1

Spring has removed these incorrect @Nullable annotations from Specification class as part of DATAJPA-1766.

This will work fine now after using the Spring version in which above defect was fixed.

Smile
  • 3,832
  • 3
  • 25
  • 39