Friday, April 25, 2008

closures and you

So I'm diving into dynamic programming with Groovy and I love it. I consider myself an expert Java & C++ programmer, but I'm definitely having to do some re-learning with dynamic languages. I think its like when you encounter someone who, for some reason or another, really doesn't grasp object oriented methodologies. Its a way of thinking and designing your software that you really just have to understand. I think programming in dynamic languages, while very different, follow the same learning process. And I'm definitely in it.

So lets start with closures, probably the most verbalized features of dynamic languages.


Obviously the most famous is iterating a list. Lets say I want to print out every element in a list... obviously I could do the following in straight java.

Vector list = new Vector();
// add stuff to the list
for ( Object x : list)
System.out.println(x);

In groovy I can do:

def list = ["one","two","three"]
list.each { println ${it}}

The idea is I actually pass the list a segment of "code" to execute on itself. But wait, it gets better.

Lets say I want to create a function that will do something n times... easy in Groovy:

def doSometing(number, Closure c) {
0.upto(number) {c}

}

// now you can call the method like this:
doSomething (4) { println "Say Hello" }

Pretty smooth huh? Obviously the possibilities are endless and, possibly dangerous. When passing a closure to an object, you basically give it permission do do whatever it wants

class Hello {
String name
String important = "DON'T CHANGE"

def Hello (name, Closure c) {
this.name = name

c()
}
}


I can then create a Hello object like this

def h = new Hello("Jonathan" ) { this.important = "BAD"}

And the Hello object's important field will be changed, even if I make it private. Makes it a little difficult to create well-formed and protected libraries.

1 comment:

Anonymous said...

Does java not have closures? I wouldclassify closures as a functional language concept rather than a dynamic language concept. When I think of dynamic language features, I think of blurring the line between compile-time and runtime (metaprogramming) and non-static type system. Afterall , C# has closures, and it's definitely not a dynamic language. I suppose it's true that dynamic languages tend to embrace functional concepts though.

I'm not familiar with groovy, but your example is pretty interesting. having the "this" pointer be the instance you're constructing seems pretty counter-intuitive. I would expect closure semantics to capture the "this" from the outer scope, and I certainly wouldn't expect to be able to violate visibility cf a private member like that.