java 中具有多个变量的复杂 if/else 逻辑

Complex if/else logic in java with multiple variables

可以有两种类型的组 - 私人和 public。每个组都可以有成员。我有三个参数 id、includePrivate、includePublic 将按照以下规则传递到 return 组的方法中。 例如。

public List<Group> getListofGroups(String id, Boolean isPrivate, Boolean   isPublic){}
  1. 所有群组{}
  2. 所有私人群组{"includePrivate":正确}
  3. 所有public组{"includePublic":正确}
  4. 所有拥有成员身份的私人群组{"id":"id1", "includePrivate": true }
  5. 所有具有成员身份的私人群组 + 所有 public 群组 {"id":"id1", "includePrivate": true, "includePublic": true }

实现这个复杂的 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();
}........

您可以使用 "null means don't care" 范例。类似于:

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());
}

类似这样的东西,并没有那么复杂,假设 null 表示 false:

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 子句,但由于您没有说...