Adeel Ansari Adeel Ansari - 1 month ago 14
Groovy Question

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
if
s here?

Answer

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