Reputation: 35928
In my list method I will be passing several filters from the client side. Currently I have a long list of if/else blocks that get executed based on the params coming in.
I'm wondering if there is a better way to approach this?
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
}
Below are the params I'm getting for few of the requests:
[Column1:somevalue, action:[GET:list], controller:somecontroller]
[Somecolumn:someothervalue, action:[GET:list], controller:somecontroller]
Is there a pattern I can use to solve this problem before it gets out of hand
Upvotes: 1
Views: 163
Reputation: 50245
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.
Upvotes: 3