Java Reference
In-Depth Information
In this case I'll implement the steps in a simple script; later, it could be converted to a class
for integration purposes.
2.2.1. Assembling the URL with query string
To start, I need a variable to represent the base URL. In a Groovy script you don't actually
have to declare any types at all. If you declare a type the variable becomes local to the
script. If not, it becomes part of the “binding,” which is discussed in the next chapter. Here,
because I know the URL will be contained in a string before I convert it, I'll declare the
variable to be of type java.lang.String :
String base = 'http://chart.apis.google.com/chart?'
Groovy is optionally typed. This means you can specify a type if you want to, or you can
use the keyword def if you don't know or care. There's some debate among developers
about when to use def and when to specify a type. Dierk Koenig, lead author on the su-
perb Groovy in Action (Manning, 2007), says it this way:
Using def
If you think of a type, type it (from Dierk Koenig). In other words, if you know a variable
will be a String , or a Date , or an Employee , use that type of variable.
In my own experience, I used to use def a lot, but as time goes by I use it less and less. I
agree with Dierk, with the addition that when I'm tempted to use def I often pause a mo-
ment and try to think of an actual type before using it. Other developers have other styles,
though. That's the beauty of an optionally typed language: there's room for everybody.
I now need to append the query parameters to this URL. Rather than write the query string
directly I'm going to use a typical idiom for this type of application, which is to build a
map and then generate the query string from the map parameters. With that in mind, here's
the map of parameters:
def params = [cht:'p3',chs:'250x100',
chd:'t:60,40',chl:'Hello|World']
Search WWH ::




Custom Search