grails - Better approach to solving filters than if/else -


in list method passing several filters client side. have long list of if/else blocks executed based on params coming in.

i'm wondering if there better way 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 json } 

below params i'm getting few of requests:

[column1:somevalue, action:[get:list], controller:somecontroller] [somecolumn:someothervalue, action:[get:list], controller:somecontroller] 

is there pattern can use solve problem before gets out of hand

i don't think there pattern involved, can drill code down few lines using elvis operators , removing redundancy of creating criteria:

def list() {     def list = []     def somecolumnvalue = params.column1 ?: params.column2 ?: null     def statusvalue     = params.filter == 'failed'     list = mymodel.withcriteria{ //can use createcriteria         if(somecolumnvalue) {             eq("somecolumn", somecolumnvalue)         } else if(statusvalue) {             eq("status", !statusvalue)            }     }     list json } 

if parameters grows in number can use like

def somecolumnvalue = params.column1 ?:                        params.column2 ?:                        params.column3 ?:                        params.column4 ?:                        null 

if there single parameter involved can use switch case blocks instead of if else.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -