A question was asked via twitter:
— Boris Kozorovitzky (@zbzzn) June 30, 2015
So, I built a simple flow chart to answer the question (created w/ draw.io)
Any other patch of a built-in object is cause for serious discussion of the problems that will ensue.
And if you think you should be writing a polyfill, stop. Go find a community supported and battle-tested polyfill library that already provides the feature you need.
Want some examples of the problems?
Imagine this: you have a global variable in a browser, called “config”. Do you think anyone else has ever accidentally or purposely created a “config” variable? What happens when you run in to this situation, and your code is clobbered by someone else’s code because they use the same variable name?
Now imagine this being done on built-in objects and methods, where behaviors are expected to be consistent and stable. If I patch a “format” method on to the String.prototype, and then you load a library that patches it with different behavior, which code will continue working? How will I know why my format function is now failing? What happens when you bring in a new developer and you forget to educate them on the patched and hacked built-in objects in your system?
Go read up on “monkey-patching” in the Ruby community. They learned these lessons the hard way, YEARS ago. You will find countless horror stories and problems caused by this practice.
Here are some examples, to get you started.
- Is Monkey Patching Really That Bad?
- Monkey Patching Is Destroying Ruby
- Monkey Patching: The Good, The Bad, The Ugly
But, what if …
NO! There is always a better way to get the feature you need. Decorator / wrapper objects are a good place to start. Hiding the implementation behind your API layer, where you actually need the behavior is also a good place to be.
The point is…
DO NOT PATCH THE BUILT-IN OBJECTS OR PROTOTYPES
Your code, your team and your sanity will thank you.