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.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With