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?
1 Answer 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.
customProperty
to the global scope, or onto thefeature
object. I think the latter is far better and keeps things a bit more namespaced.