0

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?

asked Jan 30, 2019 at 12:50
2
  • 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. Commented Jan 30, 2019 at 13:26
  • 1
    Without knowing the library or what the extended functionality is I'm afraid this question is too broad. Commented Jan 30, 2019 at 14:34

1 Answer 1

1

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.

answered Jan 31, 2019 at 16:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.