I regularily come across code that stores some custom properties in JS Objects from external libraries, for example:

/**@param OpenLayers.Feature feature */

function doSomething(feature) {
    feature.customProperty = "anything";

I disapprove of that, but I am not sure about the ideal solution to bypass this shortcut. Any ideas?

  • Personally, I see two options. Adding your customProperty to the global scope, or onto the feature object. I think the latter is far better and keeps things a bit more namespaced. – neilsimp1 Jan 30 '19 at 13:26
  • 1
    Without knowing the library or what the extended functionality is I'm afraid this question is too broad. – Greg Burghardt Jan 30 '19 at 14:34

As always, it depends on many factors.
Languages/Runtime Environments that lets you to 'open' objects and change them dynamically such as JavaScript here gives you a huge degree of freedom - and it's used heavily across frameworks (Ruby and Rails for instance).

Yet, use it without care and your software can become extremely hard to maintain, since you rely on external libraries that aren't under your control. (What if the external library decides to use 'customProperty' field in newer versions, and your system is ridden with implicit uses of this customProperty by setting/getting it ?).

I will separate my answer between data and behavior:

  • Data:
    If you interact heavily with the external library object and insert your custom data fields, it may be wise to create your own object class which will encapsulate the external library object and your custom fields separately. In this way, you can guarantee that any implicit contract you have in your system will be explicit through interacting with your class object. Plus, it's easier to maintain this single class instead of implicit references to custom fields throughout your system.

  • Behavior:
    If you don't override existing behavior of the object, see the Data suggestion.
    Else, a judicious use of overriding an external library object function will be to mediate cross-cutting concerns that you may have, without affecting the objects' original behavior.
    Other uses that may affect the objects' original behavior require an intimate knowledge of the library and its' contracts, which can be unlikely in the long run.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.