AS3 constructor has no method with the same name as the class - actionscript-3

I was reading ActionScript 3.0 Abstract Factory Design Pattern: Multiple Products and Factories, and I have the following,
private var busFactory:AbFactory;
busFactory=new BusinessFactory();
Both in BusinessFactory.as and in AbFactory.as there is no method with the same name as the class, only createProductA and createProductB. So, how could busFactory call the constructor with new BusinessFactory ?

The default constructors for both AbFactory and BusinessFactory (which the article shows inherits from AbFactory) are created by the compiler.
If you start to pass arguments to the BusinessFactory() constructor, the compiler will complain about an unexpected argument count. That's when you need to write the constructor yourself. But passing nothing means the default can be used.

Also the reason that you could set a AbFactory to a BusinessFactory means that they share the same heritage.

Related

Why does this property/function name collision compile in AS3?

In ActionScript 3.0, this compiles:
public function set func(value:Function):void
{
}
public function func():void
{
}
This doesn't:
public function set someVar44(value:int):void
{
}
var someVar44:int;
Why does the first one compile? I suppose it's possible that Adobe just specifically and arbitrarily decided to block this for variables and to allow it for functions, but allowing it for either functions or variables doesn't seem to make any sense. I'm suspicious there's more to the story here. What am I not seeing?
This is really interesting, and took a fair amount of digging to get down to (although the answer seems painfully obvious).
As you know variables/properties cannot be declared in the same scope with identical names. Therefore the set function someVar44() and the variable someVar44 are in direct conflict (besides issues with trying to initialize the variable twice). Conversely if you had tried:
public function get func(value:Function):void
{
}
you would have ran into a similar issue with a duplicate function definition error. So why does the set function seem to allow you to get past these errors? As setters and getters are known for accessing and mutating properties of a class, it would seem they are also treated as class properties as opposed to a typical method, but this is not entirely the case. In fact, only the setter appears as a property of the public interface, the getter on the other hand is a method that can read like a property.
The setter:
public function set func(value:Function):void
Is read exactly like a property of the object, and without any other properties in direct conflict with it (i.e. - there is no current property like var func.) you do not receive a compiler error.
From adobe:
set Defines a setter, which is a method that appears in the public interface as a property.
get Defines a getter, which is a method that can be read like a property.
I believe that is why you are not getting a compiler error with set method. Although if you attempt to access that set method, the priority is immediately assumed to the function func(). That is, if you attempt this.func = function():void { } you will get the error:
Error #1037: Cannot assign to a method func
I can understand logically why the first compiles (in the older compiler). When considering an instance of the object, getting the obj.func property should return the member function you've defined, while setting the obj.func property should call the setter you've defined. This doesn't seem to be an ambiguity to me, though as we've seen, the runtime disagrees with me.
In the second case, you've defined a var (which defaults to the internal scope since you didn't say public, but that's another story) which, being externally visible, implicitly defines a getter and setter. So if someone sets the obj.someVar44 property of your object, are they calling the setter or setting your variable value? It's clearly an ambiguity and a duplicate definition.

Actionscript 3 - passing custom class as parameter to custom class where parameter class not constructed

Hi and thanks in advance,
I have a custom class being constructed from my main class. In the custom class it has another custom class that is passed in as a parameter. I would like to strictly type the parameter variable but when I do, 'the type is not a compile type constant etc'.
This, I understand, is because the custom class used as a parameter has not yet been constructed.
It all works when I use the variable type ( * ) to type the parameter.
I suspect this is a design flaw, in that I am using an incorrect design pattern. It is actually hand-me-down code, having received a large project from someone else who is not entirely familiar with oop concepts and design patterns.
I have considered using a dummy constructor for the parametered class in my main class but the passed in class also takes a custom class (itself with a parametered constructor). I am considering using ... (rest) so that the custom classes' parameters are optional.
Is there any other way to control the order of construction of classes? Would the rest variables work?
Thanks
(edit)
in main.as within the constructor or another function
var parameter1:customclass2;
customclass1(parameter1);
in customclass1 constructor:
public function customclass1(parameter1:customclass2)
{
....
Flash complains that the compiled type cannot be found when I use the data type customclass 2 in the paramater. It does not complain when I use the variable data type * or leave out the data type (which then defaults to * anyway). I reason that this is because customclass2 has not yet been constructed and is therefore not available to the compiler.
Alternatively, I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
There are over 10,000 lines of code and the whole thing works very well. I am rewriting simply to optimise for the compiler - strict data typing, error handling, etc. If I find a situation where inheritance etc is available as an option then I'll use it but it is already divided into classes (at least in the main part). It is simply for my own peace of mind and to maintain a policy of strict data typing so that compiler optimization works more efficiently.
thnx
I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
So if you don't have the class written anywhere what can the compiler do ? It is going to choke of course. You either have to write the CustomClass class file or just use "thing:Object" or "thing:Asteriks". It's not going to complain when you use the "*" class type because it could be anything an array, string, a previously declared class. But when you specify something that doesn't exists it will just choke, regardless of the order the parameters are declared in.

Why do static Create methods exist?

I was wondering, why do static Create methods exist?
For instance, why use this code:
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(inputUri);
over this code:
System.Xml.XmlReader reader = new System.Xml.XmlReader(inputUri);
I cannot find the rationale for using one over the other, and can't find any relation between classes who use this construct over the other.
Can anyone shed some light on this?
XmlReader is an abstract class. You cannot instantiate it.
Providing a Create method is an instance of the factory pattern. Depending on the specified arguments a different implementation of XmlReader is chosen and returned. For example, there are validating and non-validating XmlReader implementations in the .NET framework.
A more general answer...
The reason people like these kinds of methods, known as "static factory methods", is because you can give them a name (as opposed to constructors). So if you need three different constructors, you can instead create static factory methods which have names relevant to their use.
Another reason is that a factory method doesn't really need to create new objects - it can return the same one over and over if need be.
Because it can actually create and object of derived type that you have no access to or return an abstract class (as dtb answered). This is factory method pattern.
A constructor can only be used to create instances of one specific class, while a static Create method can create an instance of different classes depending on the input.
In the case of the XmlReader class the Create method will return an XmlDictionaryReader, XmlTextReader, XmlValidatingReader or XmlNodeReader, depending on which overload you use and what parameters you send to it.
This pattern allows the XmlReader class to provide you with instances of derived classes tailored to the parameters you passed to Create. Note in particular the overloads that accept an XmlReaderSettings object. A different XmlReader subclass can be returned to you depending on your settings.
A better example is WebRequest.Create(url). Depending on the URL you pass, you may receive an HttpWebRequest, an FtpWebRequest, etc.
Because you don't have to commit to the exact class of object you get. Constructors can only construct objects from exactly one class.
Because you can give the method a meaningful name, e.g. BigInt.probablePrime(). Constructors can only have the same name as the class.
Because you can have more than one factory method for the same parameter type combination, e.g. Point.fromPolarCoords(int, int) and Point.fromCartesianCoords(int, int), but there can be only one constructor Point(int, int).
(A much more detailed answer is given in Bloch's 'Effective Java'.)
Sometimes they exist as a form of self-documentation. I have a db access component that I can instantiate either with a connection string or the name of the connection in the config file. Both of these methods take strings as a parameter so they cannot be differentiated by arguments alone. So I created a FromConnectionString(string) factory method and a FromConnectionName(string) factory method. This nuance would entirely be lost by a new Foo(bool, string) line.
The idea is that this way they can change the implementation of XmlReader and not break any user code (e.g. they can change the actual type that is returned from the Create method).
I personally don't like this approach, because it creates an inverse relationship in the XmlReader class hierarchy. Maybe they thought that the Factory pattern is an overkill?
To encapsulate object creation.

When subclassing in AS3, is a new constructor function necessary?

Basic OOP question...
I want to add a couple functions to the Array class so that my program will be amazing and make me rich and famous overnight.
So I create a new subclass NewArray which extends Array. Do I need to write a constructor method for NewArray? If I leave it blank will it just use the parent's (Array's) constructor method?
Thanks
Yes, if you leave it blank it'll use the super-class' default constructor, which in the case of an Array is actually a constructor with a default value set:
Array(numElements:int = 0)
So by default you'll be creating an array with zero elements, which I guess is probably what you want anyway.
And don't forget this note from the docs:
You can extend the Array class and override or add methods. However, you must specify the subclass as dynamic or you will lose the ability to store data in an array.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html

Why do constructors not return values?

Please tell me why the constructor does not return any value. I want a perfect technical reason to explain to my students why the constructor does not have any return type.
What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap.
This space includes all members variables and the vtbl. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields.
Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.
Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
Well, in a way it returns the instance that has just been constructed.
You even call it like this, for example is Java
Object o = new Something();
which looks just like calling a "regular" method with a return value
Object o = someMethod();
How is a constructor supposed to return a return value? The new operator returns the newly created instance. You do not call a ctor, newdoes it.
MyClass instance = new MyClass();
If the ctor would return a value, like so:
public int MyClass()
{
return 42;
}
Where would you receive the integer?
(I'm biased towards C++, so regarding other languages, take this with a grain of salt.)
Short answer: You don't want to have to explicitly check for success for every single object construction in your code.
Somewhat longer answer: In C++, constructors are called for dynamically as well as for globally and automatically allocated objects. In this code
void f()
{
std::string s;
}
there is no way for the constructor of s (std::string::string()) to return any value. Either it succeeds - then we can use the object, or it throws an exception - the we never get a chance to try to use it.
IMO, that's the way it should be.
A constructor is some method automatically called when you initialize a new instance of an object.
This method is there if you need to initialize your object to a given state and run few default methods.
Actually you can imagine the constructor always return the instance of the object created that would be a good image.
When you call a constructor the return value is the new object:
Point pt = new Point(1,2);
But within the constructor itself, you're not actually creating and returning the object; it's been created before your code starts, you're just setting up the initial values.
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
The lack of a return type reflects the fact that constructors are used differently than other functions. A return type of null, while technically accurate, doesn't reflect well the fact that the code is used as if it returns an object. However, any other return type would indicate that your code is supposed to return something at the end, which is also incorrect.
Constructor doesn’t return anything not even Void. Though some of the answers have mentioned that Constructor do return reference to the newly created object , which is not true. It’s the new operator that returns the object.
So Why constructor doesn’t return any value
Because its not supposed to return anything. The whole purpose of constructor is to initialize the current state of the object by setting the initial values.
So Why doesn’t it even return Void
This is actually a Design constraint which has been placed to distinguish it from methods. public void className() is perfectly legal in java but it denotes a method and not a constructor. To make the compiler understand that it’s a constructor , it requires a way to distinguish it.
all answers are biased towards C++/Java. there is no reason a constructor does not return a value other than the language design.
look at a constructor in a broader sense: it is a function which constructs a new object. you can write perfectly valid constructors in C:
typedef struct object object;
int object_create( object **this );
this is perfect OOP in C and the constructor returns value (this can also be called a factory, but the name depends on the intention).
however, in order to create an object automatically (to satisfy some type cast, or conversion for example), there have to be some rules defined. in C++, there is an argument-less constructor, which is inferred by the compiler if it is not defined.
the discussion is broader than what we think. Object Oriented Programming is a name which describes a way of thinking about programming. you can have OO in almost any language: all you need is structures and functions. mainstream languages like C++ and Java are so common that we think they define "the way". now look at the OO model in Ada: it is far from the model of C++ but is still OO. i am sure languages like Lisp have some other ways of doing OO.
One point that hasn't yet been discussed is that the constructor of class "foo" must be usable not only when creating instances of foo, but also when creating instances of classes derived from foo. In the absence of generics (which weren't available when Java, C++, or .net were designed) there would be no way for foo's constructor to return an object of any derived class. Therefore, what needs to happen is for the derived-class object to be created via some other means and then made available to foo's constructor (which will then be able to use the object in question as a foo when doing its initialization).
Even though the VM implementation of a constructor isn't to return any value, in practice it kind of does - the new object's reference. It would then be syntactically weird and / or confusing to be able to store one or both of the new object's reference and an additional return value in one statement.
So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
Constructor is not directly called by the user's code. It's called by the memory allocation and object initialization code in the run time. Its value is not visible to the user.
In case of C#, the syntax for declaring object is :
classname objectname= new constructor();
According to this line, if we are using assignment operator(=) then it should return some value. But the main objective of a constructor is to assign values to variables, so when we use a new keyword it creates instance of that class, and constructor assigns values to the variable for that particular instance of object, so constructor returns assigned values for that objects's instance.
We can not call constructors independently. Instead they are automatically called whenever objects are created.
Ex:
MyDate md = new Mydate(22,12,2012);
In above example new will return a memory location which will be held by md, and programatically we can not return multiple values in single statements.
So constructors can not return anything.
From what I know about OO design methodologies, I would say the following:
1)By allowing a constructor to return a value, framework developer would allow the program to crash in an instant where the returned value is not handled. To keep the integrity of the program workflow, not allowing a return value from the initialization of an object is a valid decision. Instead, language designer would suggest/force the coders to use getter/setter - access methods.
2)Allowing the object to return a value on initialization also opens possible information leaks. Specially when there are multiple layer or access modifications applied to the variables/methods.
As you aware that when object is created constructor will be automatically called So now imagine that constructor is returning an int value. So code should like this...
Class ABC
{
int i;
public:
int ABC()
{
i=0;
return i;
}
.......
};
int main()
{
int k= ABC abc; //constructor is called so we have to store the value return by it
....
}
But as you aware that stament like int k= ABC abc; is not possible in any programming language. Hope you can understand.
i found it helpful
This confusion arises from the assumption that constructors are just like any other functions/methods defined by the class. NO, they are not.
Constructors are just part of the process of object creation. They are not called like other member functions.
I would be using Java as my language in the answer.
class SayHelloOnCreation {
public SayHelloOnCreation() {
System.out.println("Hello, Thanks For Creating me!");
}
}
class Test {
public static void main(String[]args) {
SayHelloOnCreation thing = new SayHelloOnCreation(); //This line here, produces an output - Hello, Thanks For Creating me!
}
}
Now let us see what is happening here. in java, we use the new keyword to create an instance of a class. And as you can see in the code, in the line, SayHelloOnCreation thing = new SayHelloOnCreation();, the expression after the assignment operator runs before assignment is done. So using the keyword new, we call the constructor of that class (SayHelloOnCreation()) and this constructor creates an object on the Java Heap. After the object is created, a reference to that object is assigned to the thing reference of type SayHelloOnCreation.
The point that I am trying to keep here is that if constructors were allowed to have a return type, Firstly the strongly typed nature of the language would be compromised (Remember I am speaking about Java here).
Secondly, an object of class SayHelloOnCreation is created here so by default I guess the constructor returns a reference of the same type, to avoid ClassCastException.
A method returns the value to its caller method, when called explicitly. Since, a constructor is not called explicitly, who will it return the value to. The sole purpose of a constructor is to initialize the member variables of a class.