Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38143

Replacing a native Object (Array) method with a custom method: Is it safe? Compatible?

I've got an array, and it's got a method I threw onto it called add, which I use as a wrapper around push. I've found myself using push a few times when I should have used add, and now I'm thinking it would be nice to assign a reference to my add method to the array's native push. Thus, calling push on the array would call add.

Do internals depend on externally available native methods like push? How would this affect compatibility? Is this a bad idea? If so, why?

Some code:

PR.state = {
   views: []
};

_.extend(PR.state.views, {

   add: function(view) {
     var parent = view.parent;
     if ((!this.length && view instanceof PR.Views.App) || (parent && _.contains(this, parent)))
       this.push(view);
   }

});

// I am thinking:
PR.state.views.push = PR.state.views.add;

Upvotes: 0

Views: 185

Answers (2)

Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38143

What a stupid question. If I replace push with add, then what happens when I call push from add? :< :< I haven't tested it, but I suspect that while Array.prototype.push will still be available, unless I use Array.prototype.push explicitly, calling add will result in a mondo endless loop.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707476

I would strongly advise against changing the behavior of a standard array method. If you really want a custom method, then just create a new method and give it it's own unique name and use that.

Changing the behavior of existing methods could have all sorts of bad consequences:

  1. Incompatibility with code retrieved from any other source.
  2. Creates a non-standard and unexpected implementation if anybody else ever works on this project. This is like adding in a time bomb to trip up some future developer.
  3. Training yourself to use your own custom method instead of .push() is just something that a decent developer would do. Just do it.
  4. Creating a newly named method with an appropriate and descriptive name improves the readability, understandability and maintainability of your code. Replacing an existing method with something that works differently does the opposite.

It's not so bad if you just replace the method on one instance of an array, not the whole array prototype, but it's still not a good idea.

Upvotes: 2

Related Questions