1

在我的列表方法中,我将从客户端传递几个过滤器。目前,我有一长串根据传入的参数执行的 if/else 块列表。

我想知道是否有更好的方法来解决这个问题?

def list () {
  println params
  def list = []
  if (params["Column1"] != null) {
    list = Mymodel.createCriteria().listDistinct {
      eq("somecolumn", params["Column1"]);
    }
  }
  else if (params["Column2"] != null) {
    list = Mymodel.createCriteria().list {
      eq("someothercolumn", params["Column2"]);
    }
  }
  else if (params["filter"] == "failed") { 
     list = MyModel.createCriteria().list {
       eq("status", false);
     }
  }
  return list as JSON
}

以下是我为几个请求获得的参数:

[Column1:somevalue, action:[GET:list], controller:somecontroller]
[Somecolumn:someothervalue, action:[GET:list], controller:somecontroller]

有没有一种模式可以在它失控之前解决这个问题

4

1 回答 1

3

I don't think there is any pattern involved, but you can drill the code down to few lines by using Elvis operators and removing the redundancy of creating the criteria:

def list() {
    def list = []
    def someColumnValue = params.Column1 ?: params.Column2 ?: null
    def statusValue     = params.filter == 'failed'
    list = Mymodel.withCriteria{ //can also use createCriteria
        if(someColumnValue) {
            eq("somecolumn", someColumnValue)
        } else if(statusValue) {
            eq("status", !statusValue)   
        }
    }
    list as JSON
}

If the parameters grows in number then you can use something like

def someColumnValue = params.Column1 ?: 
                      params.Column2 ?: 
                      params.Column3 ?: 
                      params.Column4 ?: 
                      null

If there is only single parameter involved then you can effectively use switch case blocks instead of if else.

于 2013-08-24T04:27:04.983 回答