如何优化具有多个规范的if else语句



我正在尝试根据请求体中发送的字段创建动态搜索。我准备了许多规范和"概要规范"。(在方法中调用)如果field不同于null,我想调用它们。它工作,但问题是我永远不会知道哪个参数将开始创建条件,所以我不得不添加布尔参数,导致创建许多if else语句。代码:

public Specification<ShapeEntity> conditionalSearch(ShapeParams shapeParams) {
Specification spec = null;
boolean isFirstParam = true;
if (shapeParams.getType() != null) {
if (isFirstParam) {
spec = Specification.where(isTypeEqual(shapeParams.getType()));
isFirstParam = false;
} else {
spec = spec.and(isTypeEqual(shapeParams.getType()));
}
}
if (shapeParams.getWidthTo() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthLessThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthLessThan(shapeParams.getWidthTo()));
}
}
if (shapeParams.getWidthFrom() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthGreaterThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthGreaterThan(shapeParams.getWidthTo()));
}
}
return spec;
}

有什么方法可以优化吗?规格说明必须总是以".where"开头。作为第一个,然后我可以添加其他条件,我想有10+参数。

您可以编写一些方法来接收一些值来验证并返回布尔值。

boolean checkType(CustomObject type){
return type == null;
}

你可以检查可选的使用,它可能有助于一些if块。

Optional.ofNullable(type).ifPresent(t -> /*some operations*/);

您可以检查是否可以合并某些条件。

if (shapeParams.getType() != null && isFirstParam) {
//do something....
} else {
//do other....    
}

取决于你想达到什么效果。如果没有提供任何条件,并且希望搜索时不使用任何"where";条款你可以做

public Specification<ShapeEntity> conditionalSearch(ShapeParams shapeParams) {
Specification spec = Specification.where(null);
if (shapeParams.getType() != null) {
spec = spec.and(isTypeEqual(shapeParams.getType()));
}
if (shapeParams.getWidthTo() != null) {
spec = spec.and(isWidthLessThan(shapeParams.getWidthTo()));
}
return spec;
}

,如果你把它移到isTypeEqual返回null,你可以直接调用

Specification spec = Specification.where(null);
spec = spec.and(isTypeEqual(shapeParams.getType()));

如果你想知道在所有这些"and "之后规格仍然为空,我找到的唯一方法是这样的

public Specification<ShapeEntity> conditionalSearch(ShapeParams shapeParams) {
Specification emptySpec = Specification.where(null);
Specification spec = emptySpec;
if (shapeParams.getType() != null) {
spec = spec.and(isTypeEqual(shapeParams.getType()));
}
if (shapeParams.getWidthTo() != null) {
spec = spec.and(isWidthLessThan(shapeParams.getWidthTo()));
}
if (spec == emptySpec) {
return null;
}
return spec;
}

相关内容

  • 没有找到相关文章

最新更新