I have come across this term; and I am trying to understand it through few practical uses, if any; and how exactly is it different from overriding.
Monkey patching I guess is similar to overriding, but when you monkey patch something it typically means that you don't change the API or access to it in any way. For example (in psuedo code) lets say we wanted to change a to_int method on a built in String object to print what it is converting to the console (really silly contrived example, but it will serve this purpose):
class MyString extends String {
function to_int() {
print(this)
return super.to_int()
}
}
Here we've provided our own to_int method, but we've changed how it is accessed - now we need to create new instances of MyString rather than String to access it.
String.old_to_int = String.to_int
String.to_int = function() {
print(this)
return this.old_to_int()
}
This time we've not changed the interface or access to the method, and across the application wherever the built in String's to_int method is called, ours will be called instead. This is the basis of monkey patching :)
Cliff Rowley
Thinker, Tinkererer, Dork.
Mev-Rael
Executive Product Leader & Mentor for High-End Influencers and Brands @ mevrael.com
Whoa, hadn't heard that term for some years.
Forget about that strange name and let's call it "Changing the behavior of the original code". The name Monkey-patching basically comes from older times where you needed to do "hot patches (fixes)" or change/inject new functionality, especially into 3rd party code which you depended on, but couldn't change the original. So, you just applied a patch right on the original API and thus changed the behavior of the whole 3rd party code in your codebase.
Monkey-patching is a bad practice and was used also because design patterns like Dependency Injection weren't well known, or even didn't exist.
You can read more about Dependency Injection, in one of my earlier answers:
It is like, in JavaScript, to change or even remove native prototypes or properties on the
windowobject.The only difference between monkey-patching and overriding; is that in overriding you are making a subclass which doesn't affect the main class and any code using the original code is also not affected. Today you usually make a subclass and just inject it via DI, replacing the framework service with a custom solution for example. In monkey-patching you are changing the original.
Simple example in JS:
const Calc = { add(a, b) { return a + b; } } Calc.add(1, 2); // 3// Monkey-patching Calc.add = (a, b) => { return a - b; } Calc.add(1, 2); // -1, ow, totally unexpected for other devs // now also imagine that this Calc.add() has been used // all around your app, many things might get broken// Overriding (Which means extending in the first place) const MyCalc = Object.assign({}, Calc, { add(a, b) { return a - b; } }); MyCalc.add(1, 2); // -1, ok, this is what we wanted Calc.add(1, 2); // 3, while the original still works the same way