Java Reference
In-Depth Information
That's when I first encountered what influential blogger Steve Yegge has since referred to
as the subjugation of verbs in the kingdom of the nouns. [ 13 ] In most OO languages, meth-
ods (verbs) can only exist as part of nouns (classes). Java certainly works that way. Even
static methods that don't require objects still have to be defined inside classes somewhere.
13 “Execution in the Kingdom of Nouns,” at http://mng.bz/E4MB
The first language I learned that changed all that was JavaScript, which is an object-based
language rather than object-oriented. In JavaScript, even the classes are functions. Then,
because the methods in the classes are also functions, you wind up with functions operat-
ing inside of functions, possibly passing around references to still other functions, and sud-
denly everything gets confusing and difficult. Closures in JavaScript are confusing not be-
cause functions are difficult, but because a closure includes the environment in which it ex-
ecutes. A closure may have references to variables declared outside of it, and in JavaScript
it's easy to get lost determining the values.
I had no idea how simple closures could be until I encountered Groovy. [ 14 ] In Groovy, it's
easy enough to treat a closure as a block of code, but it's always clear where the nonlocal
variables are evaluated because there's no confusion about the current object.
14 Others can say the same about Ruby or other JVM languages. This is my history, though.
Closures
In practice, a closure is a block of code along with its execution environment.
In Groovy, the term closure is used broadly to refer to blocks of code, even if they don't
contain explicit references to external variables. Closures feel like methods and can be in-
voked that way. Consider this trivial example, which returns whatever it's sent:
def echo = { it }
assert 'Hello' == echo('Hello')
assert 'Hello' == echo.call('Hello')
The echo reference is assigned to the block of code (a closure) delimited by curly braces.
The closure contains a variable whose default name is it , whose value is supplied when
 
 
Search WWH ::




Custom Search