clean代码搜索端点:如何避免多个“if”?

yftpprvb  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(241)

如果您正在开发一个可以有一个或多个筛选器的搜索端点,并且有特定的规则来组合这些筛选器,那么如何避免使用多个“if”?

  1. private void addCriteria(ProductFilter filter, Query query) {
  2. //user does not fill anything, throws exception
  3. if (ObjectUtils.isEmpty(filter.getIds()) && !validateComboFilters(filter)) {
  4. throw new RequiredFilterException();
  5. }
  6. //user does not fill id filter but fills other filters
  7. if (ObjectUtils.isEmpty(filter.getIds()) && validateComboFilters(filter)) {
  8. query.addCriteria(Criteria.where(Constants.CREATED_AT)
  9. .gte(filter.getFromDate())
  10. .lte(filter.getToDate()));
  11. query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
  12. }
  13. //user fills id filter and one or more other filters
  14. if (ObjectUtils.isNotEmpty(filter.getIds())) {
  15. query.addCriteria(Criteria.where(Constants.ID)
  16. .is(filter.getIds()));
  17. if (filter.filterByRangeDate()) {
  18. query.addCriteria(Criteria.where(Constants.CREATED_AT)
  19. .gte(filter.getFromDate())
  20. .lte(filter.getToDate()));
  21. }
  22. if (filter.filterByStatus()) {
  23. query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
  24. }
  25. }
  26. }
aydmsdu9

aydmsdu91#

可能是这样的。我没有在编译时检查它,但我认为一般的方法或多或少是正确的。

  1. private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_IDS = (filter, query) -> {
  2. boolean res = ObjectUtils.isNotEmpty(filter.getIds());
  3. if (res)
  4. query.addCriteria(Criteria.where(Constants.ID).is(filter.getIds()));
  5. return res;
  6. };
  7. private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_STATUS = (filter, query) -> {
  8. boolean res = filter.filterByStatus();
  9. if (res)
  10. query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
  11. return res;
  12. };
  13. private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_DATE_RANGE = (filter, query) -> {
  14. boolean res = filter.filterByRangeDate();
  15. if (res)
  16. query.addCriteria(Criteria.where(Constants.CREATED_AT)
  17. .gte(filter.getFromDate())
  18. .lte(filter.getToDate()));
  19. return res;
  20. };
  21. private void addCriteria(ProductFilter filter, Query query) {
  22. boolean added = ADD_CRITERIA_IDS.apply(filter, query);
  23. added |= ADD_CRITERIA_STATUS.apply(filter, query);
  24. added |= ADD_CRITERIA_DATE_RANGE.apply(filter, query);
  25. if (!added)
  26. throw new RequiredFilterException();
  27. }
展开查看全部

相关问题