Anonymous classes are Groovy’s bag

Posted by: Andrew Glover on 2009-08-04 15:34:00.0

Because it’s my bag, I’ve found that many Java developers aren’t aware of how to leverage anonymous classes. Indeed, they are an extremely handy feature, which can yield concise, but expressive code (even in Java, baby). Briefly, an anonymous class is

a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator.

Succinct is such a hip word, man, don’t you think?

Anonymous class are most commonly leveraged in GUI coding, but they aren’t limited to such domains. For example, in Java, you can define simple interfaces that never truly have a formal implementing class (that is, there isn’t a related source file that implements the said interface). The interface can then be a type that is returned by, say, a formal class’s method and clients of that method simply work with the interface type (via polymorphism).

For instance, in Java, you can define a simple interface like so:

public interface IResult {
 boolean wasSuccessful();
 String resultData();
}

There is nothing special going on in this interface — note, in Java, interface methods are, by default, public so there is no need to actually type public. Some people sincerely dislike the bogue “I” prefix on interfaces — I actually prefer to name interfaces with a “able” suffix — i.e. Resultable, but that doesn’t necessarily read well in this case.

Even though I’ve now defined an interface, I don’t have to implement it — I can leverage it via anonymity — for instance, imagine a class with a method defined as getResult, which had a signature like so:

public IResult getResult(){
 //...
}

I could go old-school and create a new class, say Result, which implements IResult or I could bag that option all together and simply return an anonymous class as a part of the getResult method like so:

public IResult getResult(){
 //....blah blah blah do stuff
 return new IResult(){
   public boolean wasSuccessful(){
     return true;
   }
   public String resultData() {
     return "blah blah blah";
   }
  };
}

Note how in the code above, the method returns an unnamed instance of IResult — the syntax is fairly straightforward too — simply new up the interface type and implement the methods on the fly, baby!

The Groovy language does not formally support the creation of anonymous inner classes. Nevertheless, to quote my friend Andres Almiray’s thought — “or does it?” — needless to say, you can leverage anonymous inner classes in Groovy, via Map coercion.

Using the same IResult type (in fact, the same type defined in Java, that is, the interface is a .java file, man), in Groovy, I can have a method also called def getResult (if you don’t like the def feel free to insert IResult); however, rather than returning a class definition, you can simply return a Map (where each key is the interface’s method name and the corresponding value is the method’s implementation) that has been “casted” to your desired type via the as keyword in Groovy.

For example, in Groovy, this code returns an anonymous IResult type:

return [ resultData:{
   return "blah blah blah"
  },
  wasSuccessful: {
   return true
 }] as IResult;	

Anonymous classes are an extremely hip feature — in both Java and Groovy — and while the syntax is slightly different, the benefits are the same, baby. In fact, this pattern of leveraging interfaces makes integration between Java and Groovy code seamless. That is, when you leverage objects defined in Groovy in Java code, interfaces become important again (interfaces leveraged strictly within Groovy to Groovy code can get in the way as polymorphism is overturned with “duck typing“) — in these cases, it makes a lot of sense to have Groovy methods returning interface types to Java and in such circumstances, Java code won’t have to concern itself with implementing types — this code leverages interface types.

Polymorphism, succinct code, and fewer lines of code to manage overall. Now what’s not to like about that?

You can now follow The Disco Blog on Twitter, baby!


be the first to rate this blog


About Andrew Glover

Andrew is the founder of the easyb BDD framework and the co-author of Addison Wesley's "Continuous Integration", Manning's "Groovy in Action" and "Java Testing Patterns". He is an author for multiple online publications including IBM's developerWorks and Oreilly's ONJava and ONLamp portals. He actively blogs about software at thediscoblog.com.