Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
50
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

Closures

309

to the get method being its new value. This is convenient, but it means that if you accidentally misspell a key when trying to retrieve it you don’t get an error; instead, you wind up adding it. That’s not true when using the single-argument version of get.

Finally, when you iterate over a map using a closure, the number of dummy arguments determines how the map is accessed. Using two arguments means that the map is accessed as keys and values:

String keys1 = '' List<Integer> values1 = [] both.each { key,val ->

keys1 += '|' + key values1 << val

}

The each iterator has two dummy variables, so the first represents the key and the second the value. This closure appends the keys to a string, separated by vertical bars. The values are added to a list.

Alternatively, using a single argument assigns each entry to the specified argument, or it if none:

String keys2 = '' List<Integer> values2 = [] both.each { entry ->

keys2 += '|' + entry.key values2 << entry.value

}

Because a single dummy argument was used in the closure, I need to access its key and value properties (equivalent to invoking the getKey and getValue methods, as usual) to do the same operation as in the previous example.

Both mechanisms produce the same results:

assert keys1 == keys2 assert values1 == values2

Throughout this section I’ve used closures in examples without defining what they are. That’s the subject of the next section.

B.5 Closures

Like many developers, I started out in the procedural world. I started my career as a research scientist, studying unsteady aerodynamics and acoustics. Most of that involved numerically solving partial differential equations.

That meant that unless I wanted to write all my own libraries, I had to adopt Fortran as my professional language of choice.11 My first assignment in my first job was to take a 3000-line program my boss had written in Fortran IV12 and add functionality to

11The fact that I seriously considered writing those libraries in a different language anyway was yet another sign I was in the wrong profession.

12Shudder. Holy arithmetic-if statements, Batman. The nightmares have stopped, but it took a while.

www.it-ebooks.info

310

APPENDIX B Groovy by feature

it. The best part was that the original program had only two subroutines in it: one that was about 25 lines long, and the other 2975. Needless to say, I learned refactoring long before I knew the actual term.

I rapidly learned what at the time were considered good development practices, meaning that I wrote structured programs that used existing libraries as much as possible. It was only in the mid-90s, when I first learned Java, that I was introduced to object-oriented programming.

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, methods (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.

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 operating inside of functions, possibly passing around references to still other functions, and suddenly everything gets confusing and difficult. Closures in JavaScript are confusing not because functions are difficult, but because a closure includes the environment in which it executes. 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.

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 invoked 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 the closure is invoked. If you think of the variable like a method parameter, you’ve got the basic idea.

The closure can be invoked in one of two ways: either by using the reference as though it’s a method call, or by explicitly invoking the call method on it. Because the

13“Execution in the Kingdom of Nouns,” at http://mng.bz/E4MB

14Others can say the same about Ruby or other JVM languages. This is my history, though.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]