04.07.2013 Views

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def strings = []<br />

but when the right side is a method invocation, I’ll type the left:<br />

List strings = someMethod('Hello', 'Groovy', 'World')<br />

and I often add the generic type even though Groovy ignores it—again as a selfdocumentation<br />

practice and not because it has any other runtime effect. The same goes<br />

for the return type and parameter type(s) of methods; if it’s void, I specify void some<br />

Method(...) instead of def someMethod(...), so the caller knows that there’s nothing<br />

being returned.<br />

each is a convenient way of looping, but I rarely use it, because it has almost no benefit<br />

over the for/in loop. For example, I would use:<br />

for (string in strings) { ... }<br />

instead of:<br />

strings.each { string -> ... }<br />

because they’re equivalent, basically the same number of characters, and both are nullsafe.<br />

And the for loop has the benefit that you can break out of it if there’s a reason to<br />

stop looping, whereas each cannot, because returning from the closure that you pass to<br />

the each method returns from the closure, not each.<br />

Of course, these are arguments about preferences—there’s no right or wrong here. And<br />

I will certainly drop the type of a method parameter if it makes testing easier by letting<br />

me substitute a more convenient value that uses duck typing.<br />

Closures Versus Methods<br />

Another example of being “too groovy” is using a closure as a method where you don’t<br />

use any features of the closure. If you don’t set the delegate or use any other closurespecific<br />

feature, then there’s no reason to use:<br />

def foo = { -><br />

...<br />

}<br />

instead of:<br />

foo() {<br />

...<br />

}<br />

and, in fact, using the method has the not-insignificant benefit of letting you specify the<br />

return type. Plus, things like AOP and method proxying that aren’t Groovy-aware won’t<br />

work at all with closures, because they’re only treated like methods by Groovy—they’re<br />

just public fields and are ignored by Java.<br />

32 | Chapter 1: Introduction to Groovy

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!