Thursday, October 20, 2011

Groovy and Self-Learning Applications

I've recently been working on a Groovy API for the open-source project Vert.x, and I was describing some of the cool features of Groovy to my colleague Anuj. One of those cool features is the ExpandoMetaClass, which allows you to use Closures to add new methods to existing classes. Anuj made a comment that got me thinking about applications of this concept. Could we write software in Groovy that adapts to situations by attaching new methods to classes or replacing existing methods.

Here is a silly example that I'm making up on the fly here. Let's say that we have a method that performs calculations on a given numerical input, and that method ends up throwing an Exception or producing invalid results on particular inputs. We could potentially use the ExpandoMetaClass to replace the implementation of the method with one that recognizes this input and ignores it.

This specific application of the concept probably has no real-world value since there may be better ways to deal with this problem, but I think it simply illustrates the idea. I haven't done any research yet to see if others have more formally defined this application of the ExpandoMetaClass. I have to believe that many smarter people than myself have had these same types of ideas. The idea is simple, but the application is almost certainly much more complex, if at all feasible even. I'll report back with any findings when I get a chance to research the topic further.