Friday, July 23, 2004

doesNotUnderstand: and code generation

One of the things that I love about Smalltalk is that it allows you to get into the internals and do all kinds of crazy things. One of these things is be able to catch messages that an object doesn't understand and allow the object to do something meaningful. Now, this is great for proxy objects. But, I've also found it helpful in creating new languages for html. Well, generally, doesNotUnderstand: usage is frowned upon and rightfully so. It's a powerful tool to use, but not one you want to use a lot. First off, code becomes harder to debug because you're going through a layer of indirection. It's also hard for beginners to your code to find what you're doing. Things seem to happen by magic. Well, I've been thinking what if I could take away the last restriction? By that, make doesNotUnderstand: a direct call. Well, in Smalltalk I can do that! I can compile a method on the fly, add it to my class, and call my new method. Sure, I still pay for the initial call to doesNotUnderstand:, but subsequent calls are direct message sends. Beginners new to code will now see these auto-generated methods and things run faster. I used this technique in the HttpUnitTest framework because we wanted as concise a language as possible to describe html rules to find content. In a way, this works like Lisp macros (sort of).

I thought it was a nice way to relieve myself of a lot of mindless code and let Smalltalk write it for me. This concept is used in Squeak to fill out accessors. if you call a method and it has the same name as an instance variable, it will create the method for you. Of course, this can be turned on and off. But, it's nice to have when you're writing code. Why write simple methods if the computer can do it for you?