How can I refactor the following method in order to reduce complexity?
protected Specification<Test> createSpecification(TestCriteria criteria) {
Specification<Test> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), test_.id));
}
if (criteria.getCustomerName() != null) {
specification = specification.and(buildStringSpecification(criteria.getCustomerName(), Test_.customerName));
}
if (criteria.getAddress() != null) {
specification = specification.and(buildStringSpecification(criteria.getAddress(), Test_.address));
}
(...)
return specification;
}
The issue is that sonar is complaining about: Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.
Thanks!
Or
Use Builder Pattern... Create a builder that allows adding specifications:
So the main method just builds and returns the specification.