mercredi 9 septembre 2015

Compressing series of if-else statement in Groovy

I have a series of if-else statements in Groovy:

String invoke = params?.target
AuxService aux = new AuxService()
def output

if(invoke?.equalsIgnoreCase("major")) {
    output = aux.major()
}
else if(invoke?.equalsIgnoreCase("minor")) {
    output = aux.minor()
}
else if(invoke?.equalsIgnoreCase("repository")) {
    output = aux.repository()
}
...
else if(invoke?.equalsIgnoreCase("temp")) {
    output = aux.temp()
}
else {
    output = aux.propagate()
}

The ellipsis contains yet another 14 sets of if-else statements, a total of 19. You see, depending on the value of invoke the method that will be called from AuxService. Now I'm thinking the following to reduce the lines:

String invoke = params?.target()
AuxService aux = new AuxService()
def output = aux?."$invoke"() ?: aux.propagate()

But I think the third line might not work, it looks very unconventional. And just a hunch, I think that line is prone to error. Is this a valid code or are there any more optimal approach to compress these lines?

Aucun commentaire:

Enregistrer un commentaire