可以有两种类型的组 - 私人和公共。每个小组都可以有成员。我有三个参数id,includePrivate,includePublic要传递给一个方法,按照下面的规则返回组。 例如。
public List<Group> getListofGroups(String id, Boolean isPrivate, Boolean isPublic){}
实现这种复杂的if / else逻辑的最佳方法是什么?为这个api创建一个规则引擎是一个很好的选择吗?
For eg. if(isPrivate && isPublic && id=!null) {
return publicAndPrivateWIthMembership();
} else if(isPrivate && id=!null ) {
return privateGroupsWithMembership();
} else if((isPublic && !isPrivate) ||(isPublic && isPrivate == null) ) {
return allPublicGroups();
} else if((isPrivate && !isPublic) ||(isPrivate && isPublic == null) ) {
return allPrivateGroups();
}........
答案 0 :(得分:1)
像这样的东西,并不是那么复杂,假设null意味着错误:
public List list(String id, Boolean includePrivate, Boolean includePublic) {
boolean inclPrivate = (includePrivate != null && includePrivate);
boolean inclPublic = (includePublic != null && includePublic);
List result = new ArrayList();
if (inclPublic || ! inclPrivate)
result.addAll(getAllPublic());
if (inclPrivate && id != null)
result.addAll(getPrivateMembers(id));
else if (inclPrivate || ! inclPublic)
result.addAll(getAllPrivate());
return result;
}
当然,如果你实际上在查询数据库,你可以动态构建WHERE
子句,但是因为你没有说....
答案 1 :(得分:0)
您可以使用“null表示不关心”范例。类似的东西:
private List<Group> groups;
public List<Group> getGroups(String id, Boolean includePrivate, Boolean includePublic) {
return groups.stream()
.filter(g -> id == null || g.getId().equals(id))
.filter(g -> includePrivate == null || g.isPrivate() == includePrivate)
.filter(g -> includePublic== null || g.isPublic() == includePublic)
.collect(Collectors.toList());
}
以上做AND
逻辑。如果您想要OR
逻辑,请在一个过滤器中执行:
public List<Group> getGroups(String id, Boolean includePrivate, Boolean includePublic) {
return groups.stream()
.filter(g -> (id == null || g.getId().equals(id))) ||
(includePrivate == null || g.isPrivate() == includePrivate)) ||
(includePublic== null || g.isPublic() == includePublic)))
.collect(Collectors.toList());
}
或将谓词推迟给调用者以获得完全灵活的API:
public List<Group> getGroups(Predicate<Group> predicate) {
return groups.stream().filter(predicate).collect(Collectors.toList());
}