Is Object the preferred Associative Container in AS3? - apache-flex

I've been using Object as a way to have a generic associative array (map/dictionary) since AS3/Flex seems to be very limited in this regard. But I really don't like it coming from a C++/Java/C# background. Is there a better way, some standard class I've not come across... is this even considered good/bad in AS3?

Yes, Actionscript uses Object as a generic associative container and is considered the standard way of doing this.
There is also a Dictionary class available, flash.utils.Dictionary.
The difference is that Dictionary can use any value as a key, including objects, while Object uses string keys. For most uses, Object is preferred as it is faster and covers the majority of use cases.
You can see the details on Object here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Object.html
and Dictionary here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Dictionary.html
and the differences between them here: http://livedocs.adobe.com/flex/3/html/help.html?content=10_Lists_of_data_4.html

I'm afraid there's no native alternative to Object or Dictionary for maps and other structures. As for standard, well, it depends on how one defines standard, but there are a couple of known libraries that you might like to check out if you look for Java style collections.
Like this one:
http://sibirjak.com/blog/collections/as3commons-collections/
Also, you could take a look at this question, that has links to a couple of ds libraries (including the above one).
Collections in Adobe Flex
I wouldn't say using Objects is either good or bad practice. In the general case they are faster than any Actionscript alternative (since they are native), but less featured. Sometimes the provided functionality is good enough. Sometimes, it's a bit bare-bones, so something more structured could help you getting rid of lower level details in your code and focusing in your "domain logic", so to speak.
In the end, all of these libraries implement their data structures through Objects, Dictionaries and Arrays (or Vectors). So, if the native objects are fine for your needs, I'd say go with them. On the other hand, if you find yourself basically re-writting, say, an ad-hoc Set, perhaps, using one of these libs would be a wise choice.

Related

ECS with Go - circular imports

I'm exploring both Go and Entity-Component-Systems. I understand how ECS works, and I'm trying to replicate what seems to be the go-to document of ECS, namely http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
For performance, the document recommends to use static arrays of every component type. That is, not arrays of component interfaces (arrays of pointers). The problem with this in Go is circular imports.
I have one package, ecs, which contains the definitions for Entity, Component and System types/interfaces as well as an EntityManager. Another package, ecs/components, contains the various components. Obviously, the ecs/components package depends on ecs. But, to declare arrays of specific components in EntityManager, ecs would depend on ecs/components, therefore creating a circular import.
Is there any way of avoiding this? I am aware that normally a high level system should not depend on lower systems. I'm also want to point out that using an array of pointers is probably fast enough for my purposes, but I'm interested in possible workarounds (for future reference)
Thank you for your help!
For performance, the document recommends to use static arrays of every
component type.
I'm just going to start off saying that I may be blind, but I ctrl+f'd and read that document multiple times and didn't see anything close to that. (Certainly some optimizations could be made this way with regards to things like avoiding cache misses, but I'm dubious it in any way outweighs the clerical overhead).
There's the easy answer to the exact question you asked first, the . import. Any package with an import statement like import . "some/other/package" will treat that package's contents as its own, ignoring circular dependencies. Don't do this.
Unfortunately, without merging the packages, you won't be able to do this (without using interfaces, I mean). Don't fear, though. The article you posted explicitly says this under "implementation details".
Giving each component a common interface means deriving from a base
class with virtual functions. This introduces some additional
overhead. Do not let this turn you against the idea, as the additional
overhead is small, compared to the savings due to simplification of
objects.
It's outright telling you to use interfaces (okay, C++ virtual inheritance, but close enough). It's okay, it's necessary. Especially if you want two slightly different AI components or something, it's a godsend then.

Qt's QList: which is the canonical form of getting the number of items in a list?

Qt's QList class provides several methods for getting the number of items in the list - count, length, and size. As we all know, consistency is important, so which should be the canonical/preferred method to use of those 3?
I agree with everything #Cogwheel said, but in all honesty I would just pick one and stick with it. I think good style would dictate that if "size" sounds the best to you, then use "size" everywhere...don't alternate between "count", "length" and "size" haphazardly. That will lead to potential confusion or a lot of unnecessary trips to documentation pages.
You could try to come up with some other kind of rationale, but the language itself isn't even consistent. All the STL containers (e.g. list, vector) only provide "size", the string class provides "size" and "length", etc.
Pick your favorite (or if you have multiple developers, you should all agree on a favorite) and just stick with it.
The consistency you should work towards is within your project. You're not really going to gain anything by trying to be consistent with everyone else, unless there's some way they'd be incompatible.
That being said, there are subtle semantic differences (in English, not C++) between the names of the functions. If you can make your code clearer by taking advantage of the differences, then consistency may actually work against you.
IMHO, Any one of those. Since even different developers follow different functions within your project, the function names are quite self documented, in the sense that other developers can easily understand what the function is meant to.
I usually go with "size." Ultimately, it is a bit arbitrary, but Qt containers and STL containers both generally have a size, so it is easy to stay consistent between the two types. It's also the shortest. Whenever several solutions are basically equivalent, I always go with whichever results in the least amount of typing. It's a simple rule of thumb, so everybody on the project can usually remember it.

The standard map/associative-array structure to use in flash actionscript 3?

I'm relatively new to flash, and is confused about what I should use to store and retrieve key value pairs. After some googling I've found various map-like things to choose from:
1) Use a Object:
var map:Object = new Object();
map["key"] = "value";
The problem is that it seems to lack some very basic features. For example to even get the size of map I'd have to write a util method.
2) Use a Dictionary
What does this standard library class provide over the simple object? It seems silly for it to exist if it's functionally identical to Object.
3) Go download some custom HashMap/HashTable implementation from the web.
I've used a lot of modern languages, and this is the first time I haven't been able to find a library implementation of an associative array within 5 minutes. So I'd like to get some best-practice advice from an experienced flash developer.
Thanks!
Maybe your google foo is a bit weak today?
But you're right, the built-in Object object, doesn't provide many extra features.
Dictionaries have at least two important differences with Objects:
They can use any object as a key. For Objects, the key has to be a string (if you pass any other object, the toString() method will be implicitly called).
You can optionally set they keys to be weak referenced (this doesn't make much sense for Objects).
Anyway, there are a number of opensource libraries that implement various data structures and collection types.
Just from the top of my head:
http://lab.polygonal.de/ds/
http://sibirjak.com/blog/index.php/collections/as3commons-collections/
You should use whichever option is needed for a particular situation. There is no correct answer to say "always use 'x'".
I've found that the vast majority of times Object based dictionaries are all that's needed. They're extremely fast and easy to use and I almost never need the extra features. It converts any key to a string which works well for most situations.
Dictionary provides some extra features but I've never needed object-based keys (and I've been programming in Flex since 1.0 alpha 1). The only time I've used a Dictionary is as a hack to get access to a weak reference since Flex doesn't provide a simple weak reference class.
More complex dictionaries are available which will provide more functionality. If you really need this functionality, then they will be useful, but I wouldn't recommend jumping in to use them when a plain old Object will work find for your needs. That said, if you do turn out to need them in your application, it might be best to using the same 3rd-party dictionary everywhere in that app for consistency and easy of maintenance.

Why are getters prefixed with the word "get"?

Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)
Conventional:
person = new Person("Joey")
person.getName().toLower().print()
Alternative:
person = new Person("Joey")
person.name().toLower().print()
Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).
Thanks.
Because, in languages without Properties, name() is a function. Without some more information though, it's not necessarily specific about what it's doing (or what it's going to return).
Functions/Methods are also supposed to be Verbs because they are performing some action. name() obviously doesn't fit the bill because it tells you nothing about what action it is performing.
getName() lets you know without a doubt that the method is going to return a name.
In languages with Properties, the fact that something is a Property expresses the same meaning as having get or set attached to it. It merely makes things look a little neater.
The best answer I have ever heard for using the get/set prefixes is as such:
If you didn't use them, both the accessor and mutator (getter and setter) would have the same name; thus, they would be overloaded. Generally, you should only overload a method when each implementation of the method performs a similar function (but with different inputs).
In this case, you would have two methods with the same name that peformed very different functions, and that could be confusing to users of the API.
I always appreciate consistent get/set prefixing when working with a new API and its documentation. The automatic grouping of getters and setters when all functions are listed in their alphabetical order greatly helps to distinguish between simple data access and advanced functinality.
The same is true when using intellisense/auto completion within the IDE.
What about the case where a property is named after an verb?
object.action()
Does this get the type of action to be performed, or execute the action... Adding get/set/do removes the ambiguity which is always a good thing...
object.getAction()
object.setAction(action)
object.doAction()
In school we were taught to use get to distinguish methods from data structures. I never understood why the parens wouldn't be a tipoff. I'm of the personal opinion that overuse of get/set methods can be a horrendous time waster, and it's a phase I see a lot of object oriented programmers go through soon after they start.
I may not write much Objective-C, but since I learned it I've really come to love it's conventions. The very thing you are asking about is addressed by the language.
Here's a Smalltalk answer which I like most. One has to know a few rules about Smalltalk BTW.
fields are only accessible in the they are defined.If you dont write "accessors" you won't be able to do anything with them.
The convention there is having a Variable (let's anme it instVar1.
then you write a function instVar1 which just returns instVar1 and instVar: which sets
the value.
I like this convention much more than anything else. If you see a : somewhere you can bet it's some "setter" in one or the other way.
Custom.
Plus, in C++, if you return a reference, that provides potential information leakage into the class itself.

Use-cases for reflection

Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.

Resources