Pushing the limits of Blanchard's Law
As you might guess, I like to push the limits a bit. Hope you don't mind. (I'll even tie this question back to message based OO).
I hadn't heard of Blanchard's law, so a google search brought up this ...
Yeah but it [dynamic Java proxies] breaks Blanchard's law of code generation. Dynamic proxies basically construct classes and load them on the fly by generating code to forward interface calls to implementations. So the system relies on code generation (binary code generation in this case) to do its thing. -- tblanchard@mac.com ([link|http://lists.xml.org/archives/xml-dev/200210/msg01206.html|http://lists.xml.org...210/msg01206.html])
I'm assuming this is the Blanchard for whom the law is named.
Keeping the above quote in mind, consider the following code ...
class SlowProxy\n def initialize(target)\n @target = target\n end\n def method_missing(sym, *args, &block)\n @target.send(sym, *args, &block)\n end\nend
It uses method_missing (Ruby's equivalent of doesNotUnderstand) to forward messages to the proxy target. It works great, but is a bit slower than a hand written proxy because :method_missing overhead.
We can rewrite it slightly to do the following ...
class FastProxy\n def initialize(target)\n @target = target\n end\n\n def method_missing(sym, *args, &block)\n define_forwarding_method(sym)\n self.send(sym, *args, &block)\n end\n\n def define_forwarding_method(sym)\n self.instance_eval %{\n def #{sym.to_s}(*args, &block)\n @target.#{sym.to_s}(*args, &block)\n end\n }\n end\nend
The first time a method is called on the proxy, it dynamically defines a specific forwarding method of that name. Further calls of that same method will no longer go through the :method_missing mechanism. The code generation piece is quite similar to that in the attribute example earlier.
But since this dynamic proxy generates method definitions on the fly (just as the Java version does), does that mean this code runs afoul of Blanchard's law as well? It would seem it does.
Seems inconsistent to me.