AS3: Where are nonstatic properties stored? - actionscript-3

My question is efficiency-wise.
Let's assume I have a class foo with a complicated nonstatic function called bar.
Does having a particularly complex nonstatic function slow down the instantiation of my class? I have read a bit about the presence, in AS3, of an object's prototype, and I guess the explanation will be related.
All in all, what I'm asking is: If I have several instances of foo, does each instance actually contain the bar property, or is bar stored in the prototype?
Thanks in advance.

Actionscript is prototype based like javascript. And yes, the bytecode from your function is only stored once.

Related

Mixed Classes/Objects and Functions: Code Smell?

I'm looking at refactoring to move to OOP, since I have mandated PS5 for all users, and there are some things in my code that could really benefit from inheritance. My script has lots of utility functions that are used in various places. Some of them will make sense to make helper methods within my classes, but some will be used beyond just one class. So, is it appropriate to keep them as Functions, or is that really a code small it everything should be converted to Classes and Objects? And if a utility function is converted to OOP, what is the mechanism for sharing it between other classes? Do you use a global variable, do you create a local variable and past some how to the object that needs it?
I have spent a great deal of time writing PowerShell classes simply for the sake of exploring the what/how/why during my day-to-day work, and in doing I have started to ask myself the following questions:
Am I going to be creating multiple instances of this thing?
Do I need it to always have these specific properties & methods?
Will this make my scripts harder for me to understand later?
For question one, it will help prevent creating additional complexity on a class you're going to create only a single instance of, when it could just as easily be a series of functions & variables contained in its' own .ps1 script
For question two, you filter out unnecessary complexity even further by eliminating classes that simply don't need to be that rigidly defined. If you have two functions for a single array of strings that contains structured data inside, your time would be better spent ensuring the functions themselves are concise and well documented instead of trying to turn it into a class definition.
Lastly for question three, if you are working on scripts that either presently, or may in the future, be passed on to another individual you need to ask whether this quality of life adjustment will make the intent of your scripts more difficult to understand. This is usually not a problem, but if you're solving an inherently procedural / functional problem with OOP concepts you're simply going to obfuscate the actual solution.
Finally, to address your concern regarding sharing information between classes, simply make your class properties public if they need to be shared between instances or functions and reference those values in the scope the instance is created.
For example, say I have Class Foo with property Bar that I want to access from a script function:
Class Foo {
[Int] $Bar = 0
Foo () { $Bar = 5 }
}
$MyVar = [Foo]::New()
Function GetBar() {
return $Script:MyVar.Bar
}
Write-Host GetBar

Instantiate class on variable declaration or within constructor [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Where is the “proper” place to initialize class variables in AS3
I was wondering if anyone knows wether its better to instantiate class on it's variable declaration or within a constructor? For example, this:
protected var _errorHandler:ErrorHandler = new ErrorHandler();
or this:
protected var _errorHandler:ErrorHandler;
public function someClass() {
_errorHandler = new ErrorHandler();
}
A small point I think, but I want my code to robust and efficient as possible!
Thanks
Chris
Initialization in the constructor is preferred, for readability--for being able to easily see what gets initialized when. The least readable option would be to mix these, which I can't recommend.
There is a third option that you will see AS3 programmers use:
No initialization in the variable declarations
Empty (or nearly empty) constructor
All initialization done in one or more dedicated init() functions
This approach has two things to offer:
You can easily reset the object for re-use by calling init again
You can get around the limitation that AS3 does not let you overload the constructor like other similar languages (Java/C++/C#). You might want to, for example, be able to initialize a data structure with one or more different types of objects.
As far as performance goes, I believe your two examples would compile down to the same byte code. The AS3 compiler makes a special class initializer for static declarations that are outside the constructor, but for regular member variables initialized at declaration time, I expect it just moves the initializations to inside the constructor for you. But does it move them ahead or after what is explicitly in the contructor? I don't remember, which is why I cite readability as a main reason to put everything in the constructor yourself :-)

How would you implement generics like Vector.<T>?

So, ActionScript 3 has generics with the Vector class (Vector.). I have not seen any other class that uses generics like this.
If you were to implement Vector. yourself, how would you do it?
If you are after generics then you are best off to look at Haxe. It is very similar to ActionScript 3 and compiles to a swc or swf.
Coming back to haxe post above... you can create generics in haxe and then compile the code to as3. Not tried it recently to see how it is handled, but.. http://haxe.org/doc/flash/as3gen
Well you could make a class that takes a type T as a parameter, something like this
Foo( type:* )
And then in all the methods from which you can add items to the Vector class, I wouls raise an excpetion if the type of the object passed to the method doesn't match the type I defined when I instanciated my vector class.
That being said, you probably wouldn't get very good performance from a class like that, since everytime you handle an object you need to check it's real type at runtime, where as in C++ template classes are created a compile time, so no runtime type checking needs to be done.
AS3 does not support generic class declaration. There's a good discussion here

What's the difference between closures and traditional classes?

What are the pros and cons of closures against classes, and vice versa?
Edit:
As user Faisal put it, both closures and classes can be used to "describe an entity that maintains and manipulates state", so closures provide a way to program in an object oriented way using functional languages. Like most programmers, I'm more familiar with classes.
The intention of this question is not to open another flame war about which programming paradigm is better, or if closures and classes are fully equivalent, or poor man's one-another.
What I'd like to know is if anyone found a scenario in which one approach really beats the other, and why.
Functionally, closures and objects are equivalent. A closure can emulate an object and vice versa. So which one you use is a matter of syntactic convenience, or which one your programming language can best handle.
In C++ closures are not syntactically available, so you are forced to go with "functors", which are objects that override operator() and may be called in a way that looks like a function call.
In Java you don't even have functors, so you get things like the Visitor pattern, which would just be a higher order function in a language that supports closures.
In standard Scheme you don't have objects, so sometimes you end up implementing them by writing a closure with a dispatch function, executing different sub-closures depending on the incoming parameters.
In a language like Python, the syntax of which has both functors and closures, it's basically a matter of taste and which you feel is the better way to express what you are doing.
Personally, I would say that in any language that has syntax for both, closures are a much more clear and clean way to express objects with a single method. And vice versa, if your closure starts handling dispatch to sub-closures based on the incoming parameters, you should probably be using an object instead.
Personally, I think it's a matter of using the right tool for the job...more specifically, of properly communicating your intent.
If you want to explicitly show that all your objects share a common definition and want strong type-checking of such, you probably want to use a class. The disadvantage of not being able to alter the structure of your class at runtime is actually a strength in this case, since you know exactly what you're dealing with.
If instead you want to create a heterogeneous collection of "objects" (i.e. state represented as variables closed under some function w/inner functions to manipulate that data), you might be better off creating a closure. In this case, there's no real guarantee about the structure of the object you end up with, but you get all the flexibility of defining it exactly as you like at runtime.
Thank you for asking, actually; I'd responded with a sort of knee-jerk "classes and closures are totally different!" attitude at first, but with some research I realize the problem isn't nearly as cut-and-dry as I'd thought.
Closures are very lightly related to classes. Classes let you define fields and methods, and closures hold information about local variables from a function call. There is no possible comparison of the two in a language-agnostic manner: they don't serve the same purpose at all. Besides, closures are much more related to functional programming than to object-oriented programming.
For instance, look at the following C# code:
static void Main(String[] args)
{
int i = 4;
var myDelegate = delegate()
{
i = 5;
}
Console.WriteLine(i);
myDelegate();
Console.WriteLine(i);
}
This gives "4" then "5". myDelegate, being a delegate, is a closure and knows about all the variables currently used by the function. Therefore, when I call it, it is allowed to change the value of i inside the "parent" function. This would not be permitted for a normal function.
Classes, if you know what they are, are completely different.
A possible reason of your confusion is that when a language has no language support for closures, it's possible to simulate them using classes that will hold every variable we need to keep around. For instance, we could rewrite the above code like this:
class MainClosure()
{
public int i;
void Apply()
{
i = 5;
}
}
static void Main(String[] args)
{
MainClosure closure;
closure.i = 4;
Console.WriteLine(closure.i);
closure.Apply();
Console.WriteLine(closure.i);
}
We've transformed the delegate to a class that we've called MainClosure. Instead of creating the variable i inside the Main function, we've created a MainClosure object, that has an i field. This is the one we'll use. Also, we've built the code the function executes inside an instance method, instead of inside the method.
As you can see, even though this was an easy example (only one variable), it is considerably more work. In a context where you want closures, using objects is a poor solution. However, classes are not only useful for creating closures, and their usual purpose is usually far different.

Immutable Collections Actionscript 3

I've been trying lately to implement some clean coding practices in AS3. One of these has been to not give away references to Arrays from a containing object. The point being that I control addition and removal from one Class and all other users of the Array receive read only version.
At the moment that read only version is a ArrayIterator class I wrote, which implements a typical Iterator interface (hasNext, getNext). It also extends Proxy so it can be used in for each loops just as a Array can.
So my question is should this not be a fundamental feature of many languages? The ability to pass around references to read only views of collections?
Also now that there is improved type safety for collections in AS3 , in the form of the Vector class, when I wrap a a Vector in a VectorIterator I lose typing for the sake of immutability. Is there a way to implement the two desires, immutability and typing in AS3?
It seems that using an Iterator pattern is the best way currently in AS3 to pass a collection around a system, while guaranteeing that it will not be modified.
The IIterator interface I use is modeled on the Java Iterator, but I do not implement the remove() method, as this is considered a design mistake by many in the Java community, due to it allowing the user to remove array elements. Below is my IIterator implemention:
public interface IIterator
{
function get hasNext():Boolean
function next():*
}
This is then implemented by classes such as ArrayIterator, VectorIterator etc.
For convenience I also extend Proxy on my concrete Iterator classes, and provide support for the for-each loops in AS3 by overriding the nextNameIndex() and nextValue() methods. This means code that typically used Arrays does not need to change when using my IIterator.
var array:Array = ["one", "two", "three"]
for each (var eachNumber:String in array)
{
trace(eachNumber)
}
var iterator:IIterator = new ArrayIterator(array)
for each (var eachNumber:String in iterator)
{
trace(eachNumber)
}
Only problem is... there is no way for the user to look at the IIterator interface and know that they can use a for-each loop to iterate over the collection. They would have to look at the implementation of ArrayIterator to see this.
Some would argue that the fact that you can implement such patterns as libraries is an argument against adding features to the language itself (for example, the C++ language designers typically say that).
Do you have the immutability you want via the proxy object or not? Note, you can have the VectorIterator constructor take a mandatory Class parameter. Admittedly this is not designer friendly at the moment, but lets hope things will improve in the future.
I have created a small library of immutable collection classes for AS3, including a typed ordered list, which sounds like it would meet your needs. See this blog post for details.
Something I do to achieve this is to have the class that maintains the list only return a copy of that list in a getter via slice(). As an example, my game engine has a class Scene which maintains a list of all the Beings that have been added to it. That list is then exposed as a copy like so:
public function get beings():Vector.<Being>
{
return _beings.slice();
}
(Sorry to revive an old thread, I came across this while looking for ways to implement exactly what Brian's answer covers and thought I would throw my 2 cents in on the matter).