Groovy Delegation Pattern Using invokeMethod and propertyMissing methods

24 / Sep / 2012 by Imran Mir 0 comments

Following DRY is practised religously in my current project. Recently, I identified a case where code repetition had long been ignored. We used to pass either a domain object or a command object in the view model. Due to this, many domain methods had to be duplicated in the command object. This was probablematic because one would easily forget to create/modify a function in the command object if it was created/modified in the domain object. The code was smelling bad. The classes were something like this:
Class College{


Class CollegeCO{
College college

//other attributes and constraints

// repetitive College methods


Groovy intercepts all methods and property access via invokeMethod and get/SetProperty property hooks. So all I needed to do was to override invokeMethod() and propertyMissing() functions in the CommandObject like this:

def invokeMethod(String name, args) {
college.invokeMethod(name, args)

def propertyMissing(String name) {

So any missing method or property call on command object was automatically delegated to the college object. This is a simple way of utilising the Delegation Patttern using Groovy.

Hope this helps.

Imran Mir


Leave a Reply

Your email address will not be published. Required fields are marked *