Hacker News new | ask | show | jobs
by friedman23 1688 days ago
Monkey patching is a terrible practice outside of unit testing and can lead to extremely difficult to debug bugs.

Also monkey patching isn't unique to python.

2 comments

FWIW I tried looking a few up and standard library seemed hit-or-miss:

JavaScript it didn't work:

  class testClass {
    constructor() { }
    
    callHoHe() {
      console.log('ho', 'he');
    }
  }

  let hi = new testClass();
  hi.callHoHe();

  testClass.callHoHe = () => {
    console.log('haha');
  }

  let heh = new testClass();
  heh.callHoHe();
This ended up just printing 'ho', 'he' twice,

For Java people didn't think it was possible:

https://stackoverflow.com/questions/47006118/is-there-any-wa...

For Java they said here that you just have to use your own similar implementation.

And for C# they have some pretty intense restrictions on overriding standard library stuff:

https://stackoverflow.com/questions/21302768/where-we-can-ov...

Golang doesn't seem to have this functionality as well:

https://stackoverflow.com/questions/37079225/golang-monkey-p...

Ps. it would have been nice to have monkey patching when dealing with btoa and atob in JavaScript, since they have different function on NodeJS vs the browser.

Pretty close with the JS, just change testClass.callHoHe to testClass.prototype.callHoHe and you're good to go. Agreed about btoa and atob, since they're globally scoped and I'm not sure if they can be overwritten...
>Ps. it would have been nice to have monkey patching when dealing with btoa and atob in JavaScript, since they have different function on NodeJS vs the browser.

The better solution is to encapsulate the class and override the methods. Monkey patching is terrible because the behavior of the function is changing at run time. If someone is not aware that you are monkey patching a function the only way for them to determine what is going on is to step through the code with a debugger.

In Scala it's possible, but only at object creation time.
This was my thought exactly. I understand why someone would want to do it. However, when a problem comes up, good luck debugging it in python.