views:

112

answers:

3

I am curious about the usage of the feature known as open classes or monkey-patching in languages like e.g. Ruby, Python, Groovy etc. This feature allows you to make modifications (like adding or replacing methods) to existing classes or objects at runtime.

Does anyone know if major frameworks (such as Rails/Grails/Zope) make (extensive) use of this opportunity in order to provide services to the developer? If so, please provide examples.

+8  A: 

Rails does this to a (IMHO) ridiculous extent.

Hank Gay
+2  A: 

.Net allows it via extension methods.

Linq, specifically, relies heavily on extension methods monkey-patched onto the IEnumerable interface.

Joel Coehoorn
I know, but that's not really what I'm asking here.
Eyvind
Perhaps if I narrow it somewhat: In .Net, linq, specifically, makes heavy use of extension methods monkey-patched onto the IEnumerable interface in order to "provide services to the deloper[sic]"
Joel Coehoorn
I don't know, though, if this really qualifies as monkey-patching, since no changes are made to the original classes/interfaces. (Thanks for pointing out the typo, BTW :))
Eyvind
+1  A: 

An example of its use on the Java platform (since you mentioned Groovy) is load-time weaving with something like AspectJ and JVM instrumentation. In this particular case, however, you have the option of using compile-time weaving instead. Interestingly, one of my recent SO questions was related to problems with using this load-time weaving, with some recommending compile-time as the only reliable option.

An example of AspectJ using load-time (run-time) weaving to provide a helpful service to the developer can be Spring's @Configuration annotation which allows you to use Dependency Injection on object not instantiated by Spring's BeanFactory.

You specifically mentioned modifying the method (or how it works), and an example of that being used is an aspect which intercepts am http request before being sent to the handler (either some Controller method or doPost, etc) and checking to see if the user is authorized to access that resource. Your aspect could then decide to return – prematurely – a response with a redirect to login. While not modifying the contents of the method per se, you are still modifying the way the method works my changing the return value it would otherwise give.

rcampbell