December 06, 2004
Open classes are the stepchildren of langage design
For a construct that can single-handedly change the way you think about programming, open classes seem a lot like collateral damage in a language design accident.
Open classes allow you to add or rewrite methods from another namespace than the one you currently write in. Should you be dissatisfied with the way a Ruby Array prints out on the screen, just go ahead and redefine String.to_s. while screwing with core classes might not make for wise examples, there are countless opportunities where open classes can save your ass.
Whenever you work with classes that don't respect Inversion of Control and fetch their dependencies on their own, being able to reopen the victimized class and add that additional bit of needed functionality is a godsent.
Unfortunately, when you don't want to rewrite, but merely extend an existing method you quickly find yourself being out of options, as there is no way to refer to the piece of code you are about to replace. There is no way to call the method-implementation of a super-class because there is no super-class. You can either rewrite a method as a whole or not at all.
Now if we open classes hadn't been denied that final ounce of love, we'd have a poor man's flavour of AOP built into every scripting language worth mentioning at this very moment.
That would have rocked.
Update: Ruby lets you alias the method you'd like to overwrite, overwrite it, and then still call the old method using the alias. Neat.
Comments
You didn't mention any specific scripting languages in your post, but you might be interested in this example of AOP with JavaScript.
http://www.jroller.com/comments/deep?anchor=aop_fun_with_javascript
It supports various types of advices, but no general pointcuts (you have to specify each method/function that you're advising).
Posted by Chris Heller (#)
Thanks for the pointer, Chris. I keep getting my ass handed to me by what Javascript has become.
Posted by Henning (#)