Posts

Showing posts from July, 2011

Monkey Patching for Mere Mortals

Sometimes you're in the middle of development and you need a custom method that is not included in the default classes that are provided. A typical example is you need a String.left method that returns everything to the left of a particular index, but oops... IntelliSense pops up and there is no String.left method sad. Sometimes writing a new class is great, but this messes with flow, because you create a separate class to store your "utility" method then 4 months you forget you even created it. Wouldn't it be fun to extend the classes dynamically? Well most dynamic languages offer this functionality. In C# this is called extension methods, in JavaScript prototypes ... Some languages make this very easy and I'll demonstrate how to create this in several languages. /// <summary> /// The following function returns all characters left of a index value len /// </summary> /// <remarks> /// <param name="s">String to