[Codenarc-developer] FW: [groovy-user] Violation of the Principle of Least Surprise?
Brought to you by:
chrismair
From: <chr...@we...> - 2011-09-19 12:30:30
|
>> I suspect a CodeNarc rule that checks that this kind of 'coercion' isn't >> normally going on outside builder code might be the right short-term answer. Something to consider. -----Original Message----- From: Paul King [mailto:pau...@gm...] On Behalf Of Paul King Sent: Monday, September 19, 2011 8:20 AM To: us...@gr... Subject: Re: [groovy-user] Violation of the Principle of Least Surprise? On 19/09/2011 9:05 PM, Russel Winder wrote: > There may be consistency of internal compiler rule application, but this > is a far cry from programmers being able to reason about their programs > given the code in front of them. The fact that there is an automated > ['a'] -> 'a' transform seems to me like a completely wrong rule — even > given that this is a dynamic language. Agreed it looks weird and good to know that Jochen has something in mind for 2.0 but just to try to give some clarification on why the behavior is there, it isn't an arbitrary replacement of a collection by its first element. It is typed argument matching going on. Java users might sometimes be surprised (a little less often perhaps) when using varargs in Java. Groovy is just letting a List be used instead of Object[] which offers a lot of convenience in some places (e.g. the SwingBuilder case already mentioned) but can be a little bit more surprising. Perhaps the example below helps (not sure): def countArgs(a) { 1 } def countArgs(a, b) { 2 } def countArgs(a, b, c) { 3 } assert countArgs(11) == 1 assert countArgs(11, 22) == 2 assert countArgs(11, 22, 33) == 3 assert countArgs([11, 22]) == 1 // list matches untyped 'a' 1st method assert countArgs(*[11, 22]) == 2 // explicit spread matches 2nd method def countIntArgs(int a, int b) { 2 } assert countIntArgs([11, 22]) == 2 // no List or Object version but // there is an (int, int) version so // explicitspread not required assert countIntArgs(*[11, 22]) == 2 // you can still do explicit spread I suspect a CodeNarc rule that checks that this kind of 'coercion' isn't normally going on outside builder code might be the right short-term answer. Cheers, Paul. --------------------------------------------------------------------- To unsubscribe from this list, please visit: http://xircles.codehaus.org/manage_email |