tags:

views:

83

answers:

4
protected int xMethod (Integer a, Integer b) {
  if (a<b)
    return 1
  else if (a>b)
    return 2
  else
    return 3
}

I wonder if there is some way of rewriting above method differently in groovy? as now is very Java style.

+2  A: 

It seems that the function just needs to return 3 different values depending on whether a is less than, equal to, or greater than b. There is already an operator in Groovy that does this:

a <=> b

The return values are -1, 0 and 1. Perhaps the best thing to do is refactor the code to use this operator instead of xMethod, if that is possible.

Of course, if the precise values 1, 2 and 3 are important and not just 3 distinct values then you can't do this.

Mark Byers
@Mark Byers - OK, what will my method look like if I change my return values to -1, 0, 1? many thanks
Sapo Mia
return (a <=> b) ?
Sapo Mia
@Sapo: You could do that, or you could just scrap the xMethod entirely.
Mark Byers
+1  A: 

How about: return (a <=> b) + 2

Jamey
This maps `-1, 0, 1` to `1, 2, 3`, but he needs it to go `1, 3, 2`. You can work out the formula so that it gets the values he wants, but I don't think it's worth the complication.
polygenelubricants
+1  A: 

If you remove the two occurrences of Integer from the signature, you can call the method with any parameters for which < is defined.

E.g.

assert x.xMethod(1, 2)==1
assert x.xMethod("2", "1")==2
assert x.xMethod(2.0, 2.0)==3

Philip Schwarz
A: 

Just to expand on Mark's answer:

protected int xMethod (Integer a, Integer b) {
    switch ( a <=> b ) {
       case -1: 1; break
       case  1: 2; break
       case  0: 3; break
    }
}

However, you have to question whether this method has any value. If the caller can be changed to accept -1, 0, 1 then the method has no reason to exist.

slim