Monkey patch

A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program). This process has also been termed duck punching.[1]

Etymology

The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime.[2] The word guerrilla, homophonous with gorilla (or nearly so), became monkey, possibly to make the patch sound less intimidating.[2] An alternative etymology is that it refers to “monkeying about” with the code (messing with it).

The definition of the term varies depending upon the community using it. In Ruby,[3] Python,[4] and many other dynamic programming languages, the term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as desired. Other forms of modifying classes at runtime have different names, based on their different intents. For example, in Zope and Plone, security patches are often delivered using dynamic class modification, but they are called hot fixes.

Applications

Monkey patching is used to:

Pitfalls

Carelessly written or poorly documented monkey patches can lead to problems:

Even if monkey patching isn't used, some see a problem with the availability of the feature, since the ability to use monkey patching in a programming language is incompatible with enforcing strong encapsulation, as required by the object-capability model, between objects.

See also

References

  1. Delabar, Eric (2008-05-02). "Duck Punching JavaScript — Metaprogramming with Prototype". Retrieved 2008-07-03.
  2. 2.0 2.1 Limi, Alexander; Shane Hathaway (2005-12-23). "Monkey patch". Plone Foundation. Retrieved 2008-07-03.
  3. "Refining Ruby". 2013-02-27.
  4. Biswal, Bimal. "Monkey Patching in Python". Software Technology Tips. Mindfire Solutions. Retrieved 9 December 2013.
  5. "Maintainable JavaScript: Don’t modify objects you don’t own". 2010-03-02.
  6. "New in Rails: Module#alias_method_chain". 2006-04-26.