Monday, April 28, 2008

Groovy Ignores Scope

Let me start out with.. I like Groovy. I haven't used it extensively yet on any of my projects, but I have done odd jobs with it.

With that said, there seems to be an important issue with Groovy in my opinion and I don't understand why there aren't many posts about it, or why it's not mentioned in the documentation, or why it still exists... Groovy does not currently enforce scoping constraints.

Take the following for example:
class PrivateMethodClass {

private static String privateMessage = 'foo'
private static String getPrivateMessage() { 'boo' }

private String privateInstanceMessage = 'instanceFoo'
private String getPrivateInstanceMessage() { 'instanceBoo' }

private static void sayHelloStatic() { println('hello static') }
private void sayHelloInstance() { println('hello instance') }
}


If you were to attempt to call any of these private variables/methods in Java, outside of the PrivateMethodClass, you would get an error when attempting to compile. In groovy on the other hand, this is totally acceptable to do.

So in Groovy this:
class PrivateMethodClassTest {

public static void main(String[] args) {
println 'attempt to call static.'

PrivateMethodClass.sayHelloStatic()

new PrivateMethodClass().sayHelloInstance()

println PrivateMethodClass.privateMessage

println PrivateMethodClass.getPrivateMessage()

println new PrivateMethodClass().privateInstanceMessage

println new PrivateMethodClass().getPrivateInstanceMessage()
}
}

Yields:
C:\projects\grovvyScopingFlaw>groovy PrivateMethodClassTest.groovy
attempt to call static.
hello static
hello instance
foo
boo
instanceBoo
instanceBoo


There is a Jira issue for this at http://jira.codehaus.org/browse/GROOVY-1875 and it is supposed to be fixed in 2.0 if I'm reading the issue ticket correctly.

I debated about whether I should post about this or not as I thought this might be old news, but as I mentioned this to people around me who are very interested in Groovy, I got a lot of surprised responses. So there it is.