Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 67 ]

Every time we use the match and find operators, behind the scenes, Groovy
transforms the regex string into a java.util.regex.Pattern object and compiles
it. The pattern operator does the same thing, and transforms the string it operates
on into a compiled Pattern object. For most applications, using find and match
directly on a pattern string is fine because the overhead of transformation and
compilation to a Pattern object is not significant. The rationale behind the pattern
operator is that complex patterns are often expensive to compile on demand, so the
precompiled pattern object will be faster to use.


A simple change to the previous code is all that is required to use a precompiled
pattern instead:


given: "A String with words we want to match"
def quickBrownFox =
"The quick brown fox jumps over the lazy dog."
and: "a matcher built via a pattern object"
def pattern = ~/\b.o.\b/
def matcher = pattern.matcher( quickBrownFox )
expect: "to match all three letter words with middle letter o"
matcher.findAll() == ['fox','dog']

Methods and closures


Closures will be dealt with in detail in the next chapter, so we won't go into them
in depth here. In order to do justice to the Groovy control structures and the special
built-in support Groovy has for collections, we need to take just a brief excursion into
closures for now.


Closures are snippets of Groovy program code enclosed in curly braces. They can be
assigned to an instance property, or a local variable, or even passed as parameters to
a method. In Java, program logic can only be found in class methods. The inclusion
of static member functions in classes gives some flexibility to Java in allowing
methods to be invoked outside of the context of an object instance.


In Groovy, methods can exist both inside classes and outside of classes. We already
know that Groovy scripts get compiled to classes that have the same name as the
script. Groovy methods within scripts just get compiled into member methods of the
script class. Groovy has a slightly different syntax from Java to support the concept
of a dynamic return type.

Free download pdf