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

时间:2016-01-06 23:21:03

标签: java if-statement rule-engine

可以有两种类型的组 - 私人和公共。每个小组都可以有成员。我有三个参数id,includePrivate,includePublic要传递给一个方法,按照下面的规则返回组。 例如。

public List<Group> getListofGroups(String id, Boolean isPrivate, Boolean   isPublic){}
  1. 所有群组{}
  2. 所有私人团体{&#34; includePrivate&#34;:true}
  3. 所有公共团体{&#34; includePublic&#34;:true}
  4. 所有拥有会员资格的私人团体{&#34; id&#34;:&#34; id1&#34;,&#34; includePrivate&#34;:true}
  5. 所有拥有会员资格的私人团体+所有公共团体{&#34; id&#34;:&#34; id1&#34;,&#34; includePrivate&#34;:true,&#34; includePublic&#34; :true}
  6. 实现这种复杂的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();
    }........
    

2 个答案:

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