Groovy Metaclass Zen: What is a duck?

“The duck is what a duck was when you created the duck.” Oi.

We’re talking a bit about adding runtime methods via Metaclass, specifically what happens to existing instances. For example, if you had a ‘Duck’ class with no methods, created an instance, and then added a ‘quack()’ method via metaprogramming, the duck you already instantiated woudn’t know how to quack.

However, if you had already declared a methodMissing handler that cleverly looked at the current Duck metaclass to see if it had a quack() method, attaching it to the existing instance on the occasion that a “pre-quack” duck was asked to quack, you could have the unquacking duck quack.

Then Kotek made me think of a curveball: what if some odd condition made me want to change the definition of quack() after many quacking instances were created? Should those new instances honor the new quack() definition, or the behavior of quack() at the time they were instantiated?

Now I know why Groovy seems to just leave this alone: the duck is what a duck was when you created the duck.

Joe Rinehart's been developing software for Web, mobile, and desktop since 1998. While he mainly now works in Java, Grails, and HTML5, he has a long history of community involvement in the Flash, Flex, and ColdFusion space. As a published author and award-winning speaker, he's bringing his skills to CompileDammit to help users new to Grails and Java. When he's not coding, he's either spending time with his family or feeding an appetite for endurance mountain bike racing. (8/9/2012 update: He's now either spending time with his family or getting over a huge knee injury caused by endurance mountain bike racing.)

Posted in Groovy/Grails
One comment on “Groovy Metaclass Zen: What is a duck?
  1. Marc Esher says:

    You can’t teach a duck new quacks. Or can you?