So in actionscript 3, instances of the Object class can be used an as associative array:
var doNotHaveSexWith:Object = new Object();
doNotHaveSexWith['mum'] = new Person(...);
doNotHaveSexWith['dad'] = new Person(...);
doNotHaveSexWith['dave'] = new Person(...);
Say I have some class, and one of it’s members is a read only ‘Object’ which contains my collection of people.
I think code readability takes a major hit if I return this ‘Object’, as how would the programmer know what to do with it?
The only way someone is going to know that it is a collection is if they read the code or the comments…
What’s the best way to signal that an Object is a collection, rather than a simple object?
Options:
-
Create a dynamic class, simply
extending from Object, called
“AssociativeArray” or something, just
so the code becomes more readable… -
Use something like the AS3
Datastructures Library, though this
seems like a bit of overkill. -
Just append the word Collection to
the end of the variable name?
For example:
var hotPeopleCollection:Object = new Object();
hotPeopleCollection['me'] = new Person(...);
hotPeopleCollection['sandrasully'] = new Person(...);
What do you think?
Update: I’ve decided to go with a custom class extending Dictionary. This way I can wrap a sensible access function around the searching function: hasOwnProperty and give the class a meaningful name.
I chose Dictionary over Object for two reasons:
- Dictionary makes more intuitive sense for a collection
- Dictionary appears to perform at O(1) for searching. See this fairly
informal dictionary vs array vs object performance benchmark
Use a dictionary.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Dictionary.html
You can still use a string for your key, or any object for that matter.
A lot of developer ( myself included ) will tell you: Never use an Object. You are basically blindfolding your compiler. Always either use a built in datatype or make your own. Now obviously you didn’t know about dictionaries in this case, but as a general rule, if you think you want to use a plain old Object datatype, think again.
Update:
Another link you might find helpful:
http://www.gskinner.com/blog/archives/2006/07/as3_dictionary.html