Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy null checking/returning

I'm fairly new to groovy so I apologize in advance if I say something stupid, but I want to find a more efficient way to do this.

In our controller we have the following logic:

def getExampleInstance() {
    if(params.id?.toString()?.isNumber()){
        return Examplet.get(params.id)
    }
    else if(params.id != null){
        return params.id.toLowerCase() == 'key' ? Example.findByIdIsNotNull() : Example.findByattributeIlike(params.id)
    }
    return null
}

There are a couple of issues with this including returning null and checking for null which I would like to get rid of. I can try:

def getExampleInstance() {
    if(params.id?.toString()?.isNumber()){
        return Example.get(params.id)
    }
    else if(params.id?.toLowerCase() == 'key'){
        return Example.findByIdIsNotNull()
    }
    //more logic here
    return null
}

But then I would end up with a more convoluted logic, and possibly still checking/returning null in order to implement the findByIlike at the end.

The contract for this method permits returning null, so that may be something I cannot fix. But I would still like to make the logic as simple as possible and avoid checking for nulls.

like image 601
janDro Avatar asked Feb 03 '26 15:02

janDro


1 Answers

Not sure 100% what you're after, but an alternative might be to try a Groovy switch statement?

def getExampleInstance() {
    switch( params.id ) {
        // Is it an integer, or a string representation of an integer?
        case Integer:
        case ~/[0-9]+/:
            return Example.get( "$params.id".toInteger() )

        // Is it the word "key"?
        case 'key':
            return Example.findByIdIsNotNull()

        // Is it null?
        case null:
            println "params.id was null"
            break

        // Otherwise, it's something else
        default:
            println "No idea how to handle $params.id"
    }
}
like image 113
tim_yates Avatar answered Feb 05 '26 06:02

tim_yates