A style question concerning polymorphic dispatch

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

A style question concerning polymorphic dispatch

Paul Bennett
There are situations where I want to determine some behavior on the basis of class (i.e. polymorphic dispatch), but I don't want to do it in the normal way (by defining and overriding a method on the set of possible classes). The most usual case for this is when I can't or won't add a method to the class (e.g it's in a jar, or another project I don't want to corrupt with unrelated detail ). 

I can think of 3 ways to do this:

  1. A switch statement on the object class: e.g switch(someObj.class) case Type1: ...; case: Type2 ... }
  2. A Category: use(MyCategory) { someObj.polyMethod() }
  3. An Expando: Type1.metaClass.polyMethod = {...} ... Type2.metaClass.polyMethod = {...} etc.

My question is: when should I use each? I have some informal rules, but I'm interested in some other feedback. My criteria are:

  • If I only want to do it in one method, I use a switch
  • If I only want to do it multiple places in a single class, I use a Category class defined as a private static class in that class file
  • Otherwise, I'll set up a static block somewhere to do add methods using an Expando

Any other thoughts? 

Are there any other ways of doing it? 

I'm using 1.8.6 right now, so the new 2.0 feature of using a Category to add behavior without using the 'use' construct is not available to me - but I would lump that into #3, as it's just another global way of achieving the same thing