Monkey patch

From Wiki @ Karl Jones dot com
Jump to: navigation, search

A monkey patch is a way for a computer program to extend or modify supporting system software locally (affecting only the running instance of the program).

Applications

Monkey patching is used to:

  • Replace methods / attributes / functions at runtime, e.g. to stub out a function during testing;
  • Modify/extend behavior of a third-party product without maintaining a private copy of the source code;
  • Apply a patch at runtime to the objects in memory, instead of the source code on disk;
  • Distribute security or behavioral fixes that live alongside the original source code (an example of this would be distributing the fix as a plugin for the Ruby on Rails platform).

Pitfalls

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

  • They can lead to upgrade problems when the patch makes assumptions about the patched object that are no longer true; if the product you have changed changes with a new release it may very well break your patch. For this reason monkey patches are often made conditional, and only applied if appropriate.
  • If two modules attempt to monkey patch the same method, one of them (whichever one runs last) "wins" and the other patch has no effect, unless monkey patches are written with a pattern like alias_method_chain.
  • They create a discrepancy between the original source code on disk and the observed behaviour that can be very confusing to anyone unaware of the patches' existence.

Quotes

"If it walks like a duck and talks like a duck, it’s a duck, right? So if this duck is not giving you the noise that you want, you’ve got to just punch that duck until it returns what you expect."

-Patrick Ewing on Monkey/Duck patching in RailsConf 2007.

See also

External links