Adeel Ansari
Adeel Ansari

Reputation: 39907

Any idea, how to avoid if statements here

Here is the code,

    User.createCriteria().list(offset: filter.offset, max: filter.max) {
        if (filter.first-name) eq('firstName', filter.first-name)
        if (filter.last-name) eq('lastName', filter.last-name)
        if (filter.email) eq('email', filter.email)
        if (filter.status) eq('status', filter.status)
        if (...) ...
        .
        .
        order(filter.sort, 'desc')
        order('name')
    }

Is there any way to avoid ifs here?

Upvotes: 0

Views: 86

Answers (2)

V H
V H

Reputation: 8587

And to make it even less readable but less repetitive you could include a map of your searchable items and try something like this :

filter.searchList=[first-name:'firstName',last-name:'lastName',
email:'email', status:'status']
User.createCriteria().list(offset: filter.offset, max: filter.max) {
     filter.searchList?.each { k,v ->
      !(filter."${k}" ?: eq(v, filter."${k}")
     }
    .
    .
    order(filter.sort, 'desc')
    order('name')
}

Upvotes: 1

Will
Will

Reputation: 14559

What about a map?

User.createCriteria().list(offset: filter.offset, max: filter.max) {
    [
        'firstName' : filter.first-name,
        'lastName'  : filter.last-name,
        'email'     : filter.email,
        'status'    : filter.status
    ].findAll { it.value }.each { eq it.key, it.value }

    order(filter.sort, 'desc')
    order('name')
}

It could be even more dynamic, simply listing the property names.


Update: what about using closures as keys?

User.createCriteria().list(offset: filter.offset, max: filter.max) {
    [
        { eq 'firstName', it } : filter.first-name,
        { eq 'lastName', it }  : filter.last-name,
        { eq 'email', it }     : filter.email,
        { eq 'status', it }    : filter.status,
        { lt 'dob', it }       : filter.dob
    ].findAll { it.value }.each { it.key(it.value) }

    order(filter.sort, 'desc')
    order('name')
}

I believe the it param can be abstracted using something like curry

Upvotes: 1

Related Questions