Method Swizzling
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. It is used to extend or modify the runtime code of dynamic languages such as
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
,
Objective-C Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
,
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
,
Groovy ''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1960s and 1970s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context. History The word ...
,
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
, and Lua without altering the original source code.


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. The word ''
guerrilla Guerrilla warfare is a form of unconventional warfare in which small groups of irregular military, such as rebels, Partisan (military), partisans, paramilitary personnel or armed civilians, which may include Children in the military, recruite ...
'', nearly homophonous with ''
gorilla Gorillas are primarily herbivorous, terrestrial great apes that inhabit the tropical forests of equatorial Africa. The genus ''Gorilla'' is divided into two species: the eastern gorilla and the western gorilla, and either four or five su ...
'', became ''monkey'', possibly to make the patch sound less intimidating. An alternative etymology is that it refers to “monkeying about” with the code (messing with it). Despite the name's suggestion, the "monkey patch" is sometimes the official method of extending a program. For example, web browsers such as
Firefox Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements curr ...
and
Internet Explorer Internet Explorer (formerly Microsoft Internet Explorer and Windows Internet Explorer, commonly abbreviated as IE or MSIE) is a deprecation, retired series of graphical user interface, graphical web browsers developed by Microsoft that were u ...
used to encourage this, although modern browsers (including Firefox) now have an official extensions system.


Definitions

The definition of the term varies depending upon the community using it. In
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
, and many other
dynamic programming language A dynamic programming language is a type of programming language that allows various operations to be determined and executed at runtime. This is different from the compilation phase. Key decisions about variables, method calls, or data types are ...
s, 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 Zope is a family of free and open-source software, free and open-source World Wide Web, web application servers written in Python (programming language), Python, and their associated online community. Zope stands for "Z Object Publishing Environm ...
and
Plone Plone is a free software, free and open source software, open source content management system (CMS) built on top of the Zope application server. Plone is positioned as an enterprise CMS and is commonly used for intranets and as part of the web ...
, security patches are often delivered using dynamic class modification, but they are called ''hot fixes''.


Applications

Monkey patching is used to: *Replace methods / classes /
attributes Attribute may refer to: * Attribute (philosophy), a characteristic of an object * Attribute (research), a quality of an object * Grammatical modifier In linguistics, a modifier is an optional element in phrase structure or clause structure whic ...
/ functions at runtime, e.g. to
stub Stub or Stubb may refer to: Shortened objects and entities * Stub, a tree cut and allowed to regrow from the trunk; see pollarding * Pay stub, a receipt or record that the employer has paid an employee * Stub period, period of time over which i ...
out a function during testing; *Modify/extend behaviour of a third-party product without maintaining a private copy of the source code; *Apply the result of a patch at runtime to the state in
memory Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembe ...
, instead of the source code on disk; *Distribute security or behavioural 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 Ruby on Rails (simplified as Rails) is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pa ...
platform);


Pitfalls

Malicious, incompetently written, and/or poorly documented monkey patches can lead to problems: *They can lead to upgrade problems when the patch makes assumptions about the patched
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
that are no longer true; a new release may very well break the 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 Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
, 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 and the observed behaviour that can be very confusing to anyone unaware of the existence of the patch. For example, the
Linux Linux ( ) is a family of open source Unix-like operating systems based on the Linux kernel, an kernel (operating system), operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically package manager, pac ...
kernel detects proprietary and other third-party modules such as the
Nvidia Nvidia Corporation ( ) is an American multinational corporation and technology company headquartered in Santa Clara, California, and incorporated in Delaware. Founded in 1993 by Jensen Huang (president and CEO), Chris Malachowsky, and Curti ...
driver, which tamper with kernel structures, so that developers will not waste their time trying to debug a problem that they cannot fix. *They can be written with malicious code in order to attack the main program, or each other. As an example, in 2009, Giorgio Maone, developer of
NoScript NoScript (or NoScript Security Suite) is a free and open-source extension for Firefox- and Chromium-based web browsers, written and maintained by Giorgio Maone, a software developer and member of the Mozilla Security Group. Features Active ...
, attacked the
Adblock Plus Adblock Plus (ABP) is a free and open-source browser extension for content-filtering and ad blocking. It is developed by Eyeo GmbH, a German software company. The extension has been released for Mozilla Firefox (including mobile), Google Chro ...
extension for Firefox, adding exceptions so that advertisements on his own websites would work. The offending code also made sure that if the user attempted to remove the exceptions, they would be added again. The spat caused widespread anger, leading to a back and forth war between new adblock rules being pushed to users, followed by Maone sabotaging the new ones, which eventually led to Mozilla stepping in to change policies regarding add-ons.


Examples

The following Python example monkey-patches the value of Pi from the standard Python math library to make it compliant with the Indiana Pi Bill. >>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3.2 # monkey-patch the value of Pi in the math module >>> math.pi 3.2


RESTART

>>> import math >>> math.pi 3.141592653589793 >>>


See also

* Polyfill *
Advice (programming) In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program. Use The pr ...
*
Aspect-oriented programming In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding behavior to existing code (an advice) ''without'' modifying t ...
*
Category Category, plural categories, may refer to: General uses *Classification, the general act of allocating things to classes/categories Philosophy * Category of being * ''Categories'' (Aristotle) * Category (Kant) * Categories (Peirce) * Category ( ...
in Objective-C *
Dynamic loading Dynamic loading is a mechanism by which a computer program can, at run time, load a library (or other binary) into memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access those var ...
*
Extension method In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype, or a type. Extension methods are features of some object-o ...
in C# *
Self-modifying code In computer science, self-modifying code (SMC or SMoC) is source code, code that alters its own instruction (computer science), instructions while it is execution (computing), executing – usually to reduce the instruction path length and imp ...


References

{{DEFAULTSORT:Monkey Patch Object-oriented programming Programming constructs