Database Reference
In-Depth Information
groovy's dynamic nature, its ability to execute code passed in as a command line
argument, the presence of closures , and its general “less is more” approach to syntax
are all factors in allowing us this syntactic freedom. however, the biggest driver is ease
of use, both in writing and reading code. Consider this line:
[6, 3, 4, 8, 2, 7].findAll{ it % 2 == 0 }.each{ println it }
We are back to finding the even numbers in an array, this time printing 6, 4, 8, and
2 on separate lines. here is a decent amount of work happening here. here are two
method calls and two closures. one of the closures returns a value. Still, it is pretty
easy to see what is going on, and there is little to no clutter. Compare that to this line,
which is what the above would look like if the three optional elements were required
instead:
[6, 3, 4, 8, 2, 7].findAll( { return it % 2 == 0; } ).each( {
println(it); } );
We have added 15 characters, plus whitespace to say the same thing, and significantly
reduced the ease both of writing and of reading the code. Because a big part of the
beauty of groovy code is the ability to say and do more things, in a readable manner, in
fewer lines, it is clear to see what a big payoff we get from having these pieces of syntax
optional.
There are some costs to having these looser syntax requirements, which should
be understood. An important one is that having optional semicolons means that
whitespace (line breaks at least) matter in a groovy program, as can be seen in this
example:
adderFunc = {
i = 1
+ 2
}
If a line of code can be interpreted to end at a line break, it will be. That means i
will be assigned a value of 1, and then a 2 will be returned. In order to add 1 and 2, the
developer will need to keep the formula on one line, move the plus sign to the end of the
previous line, or surround the formula with parentheses.
missing returns can sometimes cause methods and closures to return unexpected
values or lead the developer to forget that something is being returned at all. When
methods are defined using the def keyword instead of void or an explicit type, we may
not notice a problem with the value returned. It is usually better, if a method returns a
value, to declare what type it is.
missing parentheses may cause compiler errors that do not seem to be warranted.
The official wording is that for method calls, the parentheses can be omitted “if there is
at least one parameter and there is no ambiguity.” In reality, ambiguities can be subtle.
In practice, array and map literals as parameters are often the culprits. In particular, for
complicated reasons, parentheses are necessary when the first argument to a method
starts with a square bracket. If the developer remembers to favor readability when
deciding whether to use method call parentheses, these subtle ambiguities will mostly
be avoided.
Search WWH ::




Custom Search