One of the much touted features of dynamic languages like Ruby is the ability to change a class or object’s structure at run-time. Whilst this all sounds very clever and meta, I’ve not really seen anything that tells me why I’d want to do that. However, I’ve recently bumped into a couple of cases where I’ve found myself thinking that such an ability would be handy.
The key is when I’m receiving an object that I have no control over, generally this has been in the form of interacting with a framework like ASP.Net, where I’m given an object it defines so I can’t tweak it. I was adding routes to a collection defined by the framework, but wanted to also add the route’s name to its datatokens collection. This would have been an ideal place to override the collection’s add method, but in C# and VB.Net this isn’t possible.
Sadly, just realising that I could do this sort of thing more easily with something like Ruby doesn’t help me deal with the problem. (In this case I wrote an add method that did both actions, and changed all of the collection.add calls to use my new method. Not too hard, but it relies on no-one going in and adding other routes without paying some attention to that pattern in the future.) However, it is good to understand practical reasons for cunning language features. Knowledge is power and all that.