Should Predicates of Spring Specification be static?

1k views Asked by At

Should a Predicate of springs Specification be static or nonstatic?

The default implementation would be similar as follows:

public static Specification<Customer> byCustomerName(String name) {
    return new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.get(Customer_.name), name);
        }
    };
}

But this could also be refactored to:

private static final CUSTOMER_SPEC = return new Specification<Customer>() {
    @Override
    public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return cb.equal(root.get(Customer_.name), name);
    }
};

public static Specification<Customer> byCustomerName(String name) {
    return CUSTOMER_SPEC;
}

What should be prefered? Are Specifications threadsafe and can be used this way?

2

There are 2 answers

0
Oliver Drotbohm On BEST ANSWER

You're refactored code wouldn't even compile. There's a superfluous return, CUSTOMER_SPEC doesn't have a type, and you're referring to a name variable that doesn't exist in the scope.

I think you're overthinking the issue here and are in the process of micro-optimizing. Keeping the Specification in a static factory method should be fine.

0
user392486 On

Threadsafety wouldn't be a concern here for the implementation. You don't keep any state at all, every parameter is passed by the caller.

It could be micro-optimizing but your refactoring would be useful for example when a lot of instantiations happen of the specification. This could trigger the GC too often resulting in a noticeable lag in responsiveness.

The downside of these kind of micro-optimisations may be that you could end up with quite a memory requirement because the instance can't be GC'ed.

First back up your decision by gathering data (analysing the heap, ...) and test the impact of your solution on the application.