Of Puns and Monkey Patching

The English language is plagued by a plethora of words that have many different meanings. Often, words get twisted over time until they mean something entirely different than they originally did. I suspect this is true in most natural languages. It can be the source of many misunderstandings, quarrels, and even wars. It is no surprise then, that computer languages are also subject to these kinds of problems.

One of the first recorded instances was in the original FORTRAN implementation. It allowed the redefinition of literal values. Consequently, you could add a statement like “0 = 100” to the beginning of a program and redefine the value of 0 to be 100. This rendered all of the computation in the rest of the program suspect if not totally wrong.

Being able to redefine the meaning of words in computer languages isn’t always a source of consternation though. In some modern languages, like Ruby for instance, it is used as a mechanism for fixing software. In Ruby, functions are called methods. A method can either be anonymous, in which case it is only useful in an immediate context, for instance as an argument to another method. Or, it can be assigned as the value of a name. Then it can be executed whenever it is required by “calling” the method using its name.

Because of the way that Ruby works, you can also do something colloquially  called “monkey patching”. This works by first assigning the value of a named method to another, auxiliary  name. At this point both the original name and the auxiliary name both refer to the original method. Then, you redefine the original name. You can insert expressions before and after a call to the auxiliary method. This new method is now the new definition for the original method. Any method that called the original method will now get the newly defined method.

To give an example of how you might use this feature, suppose you wanted to print a message “Now entering myMethod” every time you called the method named myMethod. You could easily define the new method to print that message before calling the original method using the auxiliary name. Later, when you were finished using this new monkey patched method to analyze the behavior of the program, you could restore the method back to its original state by assigning the value of the auxiliary method back to the original method.

This is a feature that can easily mess up your program. But it can also let it do things that would require much more effort if done any other way. As Spider-Man’s uncle Ben is known for saying, “With great power comes great responsibility.”

There are other interesting analogies between natural languages and computer languages. We’ll discuss them more in a future blog post.