代码之家  ›  专栏  ›  技术社区  ›  SeleM

如何处理大量查询参数的if/else语句(如filter)

  •  2
  • SeleM  · 技术社区  · 6 年前

    Java的web服务的目的是开发应该处理10个 @QueryParam 至少。也就是说,假设我 10查询参数 ,最后我将使用90个if-else语句(我认为,至少)尝试构建所有可能的编译。

    例如:

    public Response getMethod(
            @QueryParam("a") List<String> a,
            @QueryParam("b") List<String> b,
            @QueryParam("c") List<String> c,
            @QueryParam("d") List<String> d,
            @QueryParam("e") List<String> e
    
           // ... etc
    ){
    
     if (a != null && b == null && c == null ...)
     {
        // bla bla bla - 1
     } 
    
     else if (a != null && b != null && c == null ...) 
     {
        // bla bla bla - 2
     }
    
    ....
    

    我的问题是如何处理这种情况?i、 e.这里是否有任何快捷方式/模式来最小化工作量?

    0 回复  |  直到 6 年前
        1
  •  2
  •   Andy    6 年前

    一般的想法是构建一个映射函数:input permutations=>outcome processor。

    为此,请使用10+布尔条件(a!=空,b!=空…)作为位字段来生成10位密钥。

    // assume a,b,c,d...j are in scope and null or not-null
    int inK = ((((a != null) ? 1 : 0) << 0 |
                ((b != null) ? 1 : 0) << 1 |
                 ...
                ((j != null) ? 1 : 0) << 9))
    
    // so now inK is a 10-bit number where each bit represents whether the
    // corresponding parameter is present.
    

    下一步…假设构建了一个映射,其中一个条目的值是表示任何键的“结果处理器”的对象。假设这个对象实现了OutcomeProcessor。

    HashMap<Integer,OutcomeProcessor> ourMap;
    

    每个结果处理器值都有一个密钥值,它是一个掩码。例如一把钥匙 值0x14表示参数'c'(4)和'e'(0x10)必须

    结果处理器需要访问它需要的任何参数,但是

    所以要建立 ourMap ,假设您知道映射和处理器实现:

    // first outcome processor (an instance of `OutcomeProcessor1` needs 'a' and 'c' input parameters
    ourMap.put(0x5, new OutcomeProcessor1());
    
    // second outcome processor (needs 'a' and 'd')
    ourMap.put(0x9, new OutcomeProcessor2());
    
    // so you'll see that if the input is 'a','c' and 'd' then both processors
    // are invoked.
    
    // repeat for all possible outcome processors
    

    for (Map.Entry<Integer, OutcomeProcessor> entry : ourMap.entrySet()) {
       int mask = entry.getKey();
       if ((mask & inK) == mask) {
          // invoke processor
          entry.getValue().method(<list of parameters>);
       }
    }
    

    真的很简单

    这种方法的一些特性:

    • 输入排列的单个实例(例如a&f&h present)可以(如果需要)产生多个结果。
    • 可以从多个输入排列调用单个结果(例如,结果处理器可能需要b&c(0x6)和输入是(a、b、c、d)或(b、c、f)-这两种输入情况都可以调用此处理器。)
    • 您可能会变得更复杂,并让OutcomeProcessor返回一个结果,清除它所服务的位。继续循环,直到所有参数都得到服务。