Implicitly Groovy
I my post yesterday I said Hello to Groovy and provided a simple helloWorld class as an example of the typical, and required, hello world example that one writes whenever starting to learn a new language.
The title of this entry is Implicitly Groovy and thats one of the really cool things about Groovy and classes. My HelloWorld code example yesterday included an explicit getter, which Sean Corfield rightly pointed out, in the context of Groovy, is overly verbose. You don't need setters and getters in Groovy they are implicitly just there. BAM! And that Grade 10 typing course I took in 1986 just became irrelevant. Say goodbye to all those setters and getters, ok I never really typed them by hand once that cfc wizard for eclipse was released and before that created a generic setProperty/getProperty function but anyway...the old code:
public class HelloWorld{
private String greeting='Hello all you Groovy People!'
String getGreeting(){
return greeting
}
}
The new code:
public class HelloWorld{
String greeting='Hello all you Groovy People!'
}
So yeah thats my class, I have a single private property called greeting and I can do something like this if I wanted to.
HelloWorld hw = new HelloWorld()
println hw.greeting
hw.greeting = 'Say hello to my little Groovy friend!'
println hw.greeting
Hello all you Groovy People! Say hello to my little Groovy friend!
Who's your daddy?
That's right implicit getters and setters. Next up closures, those sexy little things...I can't wait to get my hands on them!

Subscribe
Subscribe via RSS
Follow me on Twitter
Or, Receive daily updates via email.
Tags
adobe air ajax apple cf community cfml coldfusion examples ext flash flex google javascript max2007 max2008 misc open source programming railo software technology ui
Recent Entries
No recent entries.
Blogroll
An Architect's View
CFSilence
Rey Bango
TalkingTree

The neat thing about the implicit get/set is when you are using Spring with Groovy and just declaring a data member is sufficient to make it injectable via Spring. Here's a simple service class that - for testing purposes during development - automatically delegates to the underlying DAO:
class AdminService {
// delegate basic crud to dao
def invokeMethod(String name,args) {
userDAO."${name}"(*args)
}
IUserDAO userDAO
}
invokeMethod() is Groovy's version of CF's onMissingMethod(). Groovy automatically returns the last expression in a function (so return is optional too). In Spring - like ColdSpring - I declare that the adminService has a property called userDAO and it is wired in for me.
So little typing!
The auto wiring features are pretty impressive, I'm so used to typing so much I have to think a completely differetn way now. So much to learn so little time.