Monkey patching

Monkey patching is a powerful yet controversial technique in programming, often used to modify or extend the functionality of an object, method, or class at runtime. While it's a convenient solution for handling third-party library inconsistencies or performing unit testing, it should be used judiciously due to the potential for introducing subtle bugs or making your code more difficult to understand and maintain.

The name "monkey patching" comes from the phrase "monkey with", meaning to tamper or fiddle with something. In programming, you are essentially "tampering with" or changing parts of a module or class without altering the original source code.

To illustrate this, consider a situation where you want to add logging functionality to the 'add' method of a math library:

import MathLib from 'mathlib';

const mathLib = new MathLib();
const res = mathLib.add(2, 3);

// we can keep original implementation if we want to
// restore original implementation later on
// const originalAdd = mathLib.add;

// Let's override (monkey patch) original add
// method and replace it with our own implementation
// that supports logging
mathLib.add = function(a, b) {
    console.log(`You are adding ${a} and ${b}.`);
    return a + b;
}

This example illustrates the flexibility of monkey patching. Without having access to the source code of 'MathLib', we are able to introduce new behavior (logging) to an existing method.

👍 Pros:

👎 Cons:

The technique is often considered a 'hack' or a 'kludge', and as such, many developers advise to use it sparingly, if at all. It's important to remember that the better the design of your codebase is, the less likely you'll need to rely on techniques like monkey patching. When you do need to use it, be sure to document your code thoroughly to help maintain readability and ease of debugging.

Practice time