开发者

groovy: how to simplify/rewrite this method in groovy

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开发者_如何学Go some way of rewriting above method differently in groovy? as now is very Java style.


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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜