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

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

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

private void addCriteria(ProductFilter filter, Query query) {
//user does not fill anything, throws exception

        if (ObjectUtils.isEmpty(filter.getIds()) && !validateComboFilters(filter)) {
            throw new RequiredFilterException();
        }

//user does not fill id filter but fills other filters

        if (ObjectUtils.isEmpty(filter.getIds()) && validateComboFilters(filter)) {

            query.addCriteria(Criteria.where(Constants.CREATED_AT)
                    .gte(filter.getFromDate())
                    .lte(filter.getToDate()));

            query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
        }

//user fills id filter and one or more other filters

        if (ObjectUtils.isNotEmpty(filter.getIds())) {

            query.addCriteria(Criteria.where(Constants.ID)
                    .is(filter.getIds()));

            if (filter.filterByRangeDate()) {
                query.addCriteria(Criteria.where(Constants.CREATED_AT)
                        .gte(filter.getFromDate())
                        .lte(filter.getToDate()));
            }
            if (filter.filterByStatus()) {
                query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
            }
        }
    }
aydmsdu9

aydmsdu91#

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

private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_IDS = (filter, query) -> {
    boolean res = ObjectUtils.isNotEmpty(filter.getIds());
    if (res)
        query.addCriteria(Criteria.where(Constants.ID).is(filter.getIds()));
    return res;
};

private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_STATUS = (filter, query) -> {
    boolean res = filter.filterByStatus();
    if (res)
        query.addCriteria(Criteria.where(Constants.STATUS).in(filter.getStatus()));
    return res;
};

private static final BiFunction<ProductFilter, Query, Boolean> ADD_CRITERIA_DATE_RANGE = (filter, query) -> {
    boolean res = filter.filterByRangeDate();
    if (res)
        query.addCriteria(Criteria.where(Constants.CREATED_AT)
                                  .gte(filter.getFromDate())
                                  .lte(filter.getToDate()));
    return res;
};

private void addCriteria(ProductFilter filter, Query query) {
    boolean added = ADD_CRITERIA_IDS.apply(filter, query);
    added |= ADD_CRITERIA_STATUS.apply(filter, query);
    added |= ADD_CRITERIA_DATE_RANGE.apply(filter, query);

    if (!added)
        throw new RequiredFilterException();
}

相关问题