Database Reference
In-Depth Information
it can be very powerful to define the closure elsewhere and pass in a reference to it.
Consider the possibility of adding this:
isOdd = {
return !isEven(it) //negation operator (returns the opposite
Boolean value)
}
// I've decided I want to look for odds instead of evens.
isWhatIWant = isOdd
println testArr.findAll{ isWhatIWant(it) }
This prints [1, 3, 5, 7, 3, 5]. By having a variable to represent the work we want to
do and setting it to refer to whichever closure we want to run, we have gained the
ability to decide at runtime which block of code we want of the iterator to run for us.
This is very powerful. our code not only can decide what to do for itself (which we
may be used to), but also, by passing closures, it can designate what should be done in
other areas of the program (which we may not be so used to). Another very nice fea-
ture that closures allow is the ability to ease resource management. Worrying about
opening and closing files, network connections, and such things is one of the more
tedious, error-prone aspects of programming. These things should not be left up to us
every time we want to work with a system resource. We may fail to implement correct
exception handling or just plain forget to tidy up after ourselves. Closures provide an
excellent way to avoid this. Whenever a resource needs to be opened at the beginning
of an operation and cleaned up afterward, a method, such as the withreader method
that groovy adds to File objects, can take care of the housekeeping for us. We pass in
a closure to that method, which opens the resource, executes the code in the closure,
then closes the resource again. We get to concentrate on the important parts of the
program.
In the end, closures are one of the most important features that make groovy what
it is. They provide the exceptional expressive capability that makes this solution so
accessible for Essbase administrators to use. They are perhaps the grooviest part of
groov y.
9.4.5 Relaxed Syntax
Part of the groovy philosophy is that the language should try to maximize both read-
ability and expressiveness. The first of those terms, readability , is easy to understand,
but expressiveness may not be as clear. Expressiveness means the ability to do more
work with less code. It means saying more while writing less. A language, such as APL,
may be highly expressive, but very difficult to read without expertise in that language.
groovy attempts to allow very expressive code that can still make a good bit of sense to
a wide audience.
At times, certain syntax requirements can harm both readability and expressiveness.
With that in mind, its creators gave groovy a more relaxed syntax than Java. In particu-
lar, these three elements were made optional:
•  Explicit return statements
•  Semicolons at the ends of lines
•  Parentheses around the parameters in method calls
Search WWH ::




Custom Search