nadavc / groovykoans

A collection of small exercises in the form of unit tests, designed to get Java developers up to speed on Groovy
http://nadavc.github.com/groovykoans
Do What The F*ck You Want To Public License
264 stars 145 forks source link

Tricky Solution for 'test05_ElvisAndSafeNavigation' #26

Open abelsromero opened 10 years ago

abelsromero commented 10 years ago

I don't consider myself a Groovy expert but not a novice either and I found quite a tricky behauvior that may need some extra clarification in test05. I wrote the following solution, which may seem correct: message = 'Hello ' + userService.getLoggedInUser()?.getFirstName()?:'Anonymous' + '!' However, unless parenthesis are added as follows it does not work message = 'Hello ' + (userService.getLoggedInUser()?.getFirstName()?:'Anonymous') + '!'

Seeing why in one case it returns "Hello null" is easy, but understanding why on the other the result is "Hello Ronaldo" is not.

Seeing the missleading behauviour of elvis operator, ¿wouln'd it be nice to add a test for it, or some extra information?

Thanks

nadavc commented 10 years ago

Care to submit a pull request? :) On Aug 8, 2014 9:06 AM, "abelsromero" notifications@github.com wrote:

I don't consider myself a Groovy expert but not a novice either and I found quite a tricky behauvior that may need some extra clarification in test05. I wrote the following solution, which may seem correct: message = 'Hello ' + userService.getLoggedInUser()?.getFirstName()?:'Anonymous' + '!' However, unless parenthesis are added as follows it does not work message = 'Hello ' + (userService.getLoggedInUser()?.getFirstName()?:'Anonymous') + '!'

Seeing why in one case it returns "Hello null" is easy, but understanding why on the other the result is "Hello Ronaldo" is not.

Seeing the missleading behauviour of elvis operator, ¿wouln'd it be nice to add a test for it, or some extra information?

Thanks

— Reply to this email directly or view it on GitHub https://github.com/nadavc/groovykoans/issues/26.

EPadronU commented 8 years ago

This is a very old issue but in order to avoid further confusion for a future reader: the problem is not a "misleading behauviour of the elvis operator". The need of parenthesis shows that the cause of such problem is the simple and old operators' precedence rule. + has a higher priority than ?: so, without parenthesis the expression is evaluated as follows: ( 'Hello ' + userService.getLoggedInUser()?.getFirstName() ) ?: ( 'Anonymous' + '!' ).

Update: IMHO there's no need for an extra test or anything similar because is a matter of CS 101 and not a language quirk. Nonetheless, a comment mentioning that + has a higher priority than ?: could be useful.