Monkey Patching in D

Jacob Carlborg doob at me.com
Wed Jun 5 00:17:44 PDT 2013


On 2013-06-05 04:18, Peter Lundgren wrote:
> I'm interested in trying to write a monkey patching* library in D.
> Specifically, aiming to support mocks and stubs for unit testing.
>
> I have a couple of questions:
>
> 1) What prior art is there here? I am aware of DMocks (does this project
> still need a maintainer?).
> 2) How crazy am I for even thinking this is a good idea? Are there any
> obviously better alternatives.
>
> * I'm not sure if there is well defined terminology here (especially
> applying these ideas to compiled languages). To clarify, when I say
> monkey patch, I mean to intercept a function or method call at run-time.
> I believe, in the case of D, this would require self modifying code
> using techniques like those used here:
> http://www.yosefk.com/blog/machine-code-monkey-patching.html

I would suggestion using some kind of wrapper instead of doing true 
monkey patching. Example:

class Wrapper
{
     private Object o;
     this (Object o) { this.o = o; }

     auto opDispatch (string name, Args ...) (Args args)
     {
         // Use this function to "catch" all calls and forward as 
necessary to "o"
     }
}

http://dlang.org/operatoroverloading.html#Dispatch

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list