Synopsis
How do you declare variables in a namespace while using the use statement? (ie., without declaring the namespace with the variable name)
How do you reference namespace variables with the "use" statement without a container reference. (ie., trace(foo) rather than trace(a.foo) [seems kinda pointless if I have to state this after already switching to the namespace])
Explanation
Having read Grant Skinner's "Complete Guide to Using Namespaces", and other articles, such as Jackson Dustan's "Better OOP Through Namespaces", I'm left with the above unanswered questions. I feel as though I'm missing some basic principle, but I can't seem to get namespaces to work. The following examples are written for use with the Flash IDE, so assume the following...
locus.as
package com.atriace {
public namespace locus = "atriace.com";
}
testA.as
package com.atriace {
public class testA {
import com.atriace.locus;
locus var foo:String = "Apple";
public function testA() {}
}
}
testB.as
package com.atriace {
public class testB {
import com.atriace.locus;
use namespace locus;
public function testB() {
trace(foo);
}
}
}
Document Class:
import com.atriace.testA;
import com.atriace.testB;
var a:testA = new testA();
trace(a.foo); // results in "Apple"
var b:testB = new testB(); // compile error: variable "foo" not defined.
Issue #1
In my mind, a namespace is little more than an object to hold variables that has scope level access. Ergo, global is a namespace visible to all functions (since it's the root scope), local is namespace (specific to the current and child scopes), and so on. If true, then switching to a namespace with use should allow you to simply declare variables that happen to exist in both the local and custom namespaces. For example:
use namespace locus
var bar:String = "test"; // this now *should* exist in both local & locus scope/namespace.
Since I'm unaware of a method to iterate over a namespace like a normal object, I don't know whether this is what happens. Furthermore, I haven't seen any cases where someone has declared a custom namespace variable this way, so I assume namespace variables must always be explicitly defined.
Issue #2
You might ask, "what's the goal here?" Quite simply, we want a dynamic pool of variables and methods that any new classes can add to (within the same package). By switching to this namespace prior to calling methods, we can reduce the wordiness of our code. So, class.method() becomes just method().
In testB.as we'd fully expect an error to occur if we never imported the testA.as class and instantiated it; especially because foo isn't a static member of the class (nor do we want it to be). However, since we've instantiated foo at least once, the namespace locus should now have a variable called foo, which means that when testB.as gets instantiated, and the constructor seeks a value for foo, the namespace already has one.
Obviously, there's a flaw in this thinking since the Flash compiler complains that foo has never been declared, and the only way I can reference foo from the document class is by referencing the container (ie., a.foo rather than just switching to the namespace with use, and tracing foo directly).
For the sake of argument, neither inheritance nor static members are a solution to this dilema. This is both an excercise in learning better code techniques, and an answer to the structure of a large utility class that has complicated dependencies. Given the absence of a variable/method, you could simply code around it.
I know it's not a heavily documented topic, which is why I'm hoping some sage here may see what I'm missing. The help would be much appreciated. :)
"use namespace" is for the consumer side. You always have to include the namespace in any declaration:
MyNamespace var foobar : uint;
If you wish to add namespaced package-global variables (you shouldn't as a general rule), you have to define each one of them in a separate .as file as packages only allow one publicly-visible definition per file at the top-level.
In your example above you are using namespaces incorrectly. A namespace can span multiple classes, but does not achieve the cross-class functionality you are looking for. This is more the domain of aspect-oriented programming.
Related
What does the term 'namespace pollution' mean and why would making a method static help to prevent it?
This question seems to be similar but relates specifically to JavaScript, and the answers don't define the term.
A namespace is simply the space in which names exist (seems obvious enough now).
Let's say you have two pieces of code, one to handle linked lists, the other to handle trees. Now both of these pieces of code would benefit from a getNext() function, to assist in traversal of the data structure.
However, if they both define that function with the same name, you may have a clash. What will your compiler do when you enter the following code?
xyzzy = getNext (xyzzy);
In other words, which getNext() do you actually want to use? There are numerous ways to solve this, such as with object-oriented code, where you would use:
xyzzy = xyzzy.getNext();
and that would auto-magically select the correct one by virtue of the fact you've specified the type via the variable xyzzy itself.
But, even with mostly-OO code, there may be situations where you have a conflict, and that's where namespaces enter the picture. They allow you to place the names into their own area so as to distinguish them.
C++, as one example, places all its standard library stuff into the std namespace. If, for some reason, you need an fopen() or rand() function that works differently from the one in the library, you can place it in your own namespace to keep them separate.
Now that describes namespace clashes. Technically, namespace pollution is simply leaving your symbols in a namespace where they shouldn't really be. This doesn't necessarily lead to clashes but it makes it more likely.
The reason why making a method static (in C-like languages) has to do with the names being made available to the world outside the given translation unit (when linking, for example). With the code:
int get42 (void) { return 42; }
int main (void) { return get42(); }
both of those functions are made available to the linker.
Unless you have a need to call get42() from somewhere else, making it static:
static int get42 (void) { return 42; }
int main (void) { return get42(); }
will prevent it from polluting the namespace maintained by the linker – in C, applying the static qualifier to a file-level object or function gives it internal linkage.
It's similar to the C++ namespaces in that you can have a static int get42() in four hundred different source files and they won't interfere with each other.
Namespace pollution is a lot like pollution in general. It means that something is misplaced. In programming that means that code that should really live in separate namespaces is added to a common namespace (in some cases the global namespace). This can happen with both static and non static code, so I don't really see a scenario where static helps prevent namespace pollution.
Basically, namespaces' main function is to categorize code, and both static and non static code must be defined in a namespace somewhere.
I have a fairly big swf right now with a bit of coding already. Most vars are created in the root, but now I have a problem.
I want to reload the flash swf (reset), and for that, I need to create a function that destroys all the vars and another one that creates them. At the moment, I have a javascript function that reloads the page, but that really isnt a good solution.
The problem is that when I create a var inside a function, it doesn't get created in "MovieClip(root)", and instead is only related to the function, thus rendering my swf unable to work.
Is there a way to create vars in MovieClip(root) from within a function? Or is there an alternative to what I'm trying to do?
EDIT: Added some example code.
function SetVar():void{
var test:String= new String("foobar");
}
SetVar();
trace(test);
...and the output is:
Scene 1, Layer 'Layer 1', Frame 1, Line 7 1120: Access of undefined property test.
Which is normal, because the "var test" is not global, so it was lost when the function ended. I want to make it so the function "SetVar()" adds the vars to the root, or global.
You need to read up on how scope works.
Basically:
An object declared within another object (be it a Class, Function, Object, or Loop), is only available within that specific object or loop iteration.
Object scope is inherited by children, not by parents. So a function within a class has access to an object declared within that class, but a class does not have access to an object declared within a function
A parent (or any other object) can access objects declared within child classes, but only if it is a public object
So looking at those basic rules (they are very, very basic. If you are just starting out, I urge you to do some proper research into object scope in OOP. It is the basis of everything you will do in dozens of languages), you are declaring an object in a function and trying to access it from outside that function. This breaks Rule #1 from above.
Instead, try this:
var test:String;
function setVar():void{
this.test = 'foorBar';
}
trace(test); //output: null (undeclared)
setVar();
trace(this.test); // output: fooBar
Looking at this, I did two things:
I moved the declaration of test into global space, meaning any object in that object will have access to it
I renamed SetVar to setVar. This has nothing to do with your question, but in AS3, the standard naming conventions dictate you use lowerCaseCamelCase for all objects (including functions), UpperCaseCamelCase for all Class names, and lowercasename for all package names. Again, unrelated but it is good to learn.
Now, ideally, you would probably want to do that setVar function slightly differently. To allow for better abstraction (basically making your code as generic an reusable as possible), you would want to return the value from the function rather than manually set the variable in the function.
var test:String;
var anotherTest:String;
function setVar():String {
return 'foorBar';
}
this.text = setVar();
this.anotherTest = setVar();
trace(this.test); // output: fooBar
trace(this.anotherTest); // output: fooBar
So that allows you to use that function with any String variable imaginable. Obviously, that is not very useful here since it doesn't do any logic. But I am sure you can see how that could be expanded with more code to make it more dynamic and much more useful
EDIT: As an afterthought, I used the this keyword. In AS3 (and a few other languages), this refers to the scope of the current class (or current frame, in case of timeline frame coding). So this.test refers to a variable test declared in the scope of the frame or class.
I am not entirely sure what you are looking for because there is no code associated with your question. However I will impart a bit of information I feel relates to the subject.
if you declare your variables in the class then you can reference them from a function as such:
package{
import flash.display.MovieClip;
public class DocumentClass extends MovieClip{
public var example:String = 'dog';
public function DocumentClass(){
trace(example); // dog
testFctn();
trace(example); // frog
}
public function testFctn(){
example = 'frog'
}
}
}
if you want to reference the variable of a parent class this.parent['variableName'] can be useful too. or a sibling of your working class sharing a parent class, this.parent['childClass']['variableName'] ...
Since you are declaring the variable within the function, its scope is restricted to that function only.
Try declaring the variable outside the function and initializing it in the function instead.
You should then be able to access it from root.
But if you wish to declare a variable on root from within a function (highly unusual requirement) then you can try doing:
document["variableName'] = value;
or
root["variableName'] = value;
inside the function.
I develop a lot of frameworks for Flash games and applications. I have always prefixed my class names with a random character or two, to avoid conflict with class names that the developer may already have, for example:
class LEntity
Recently I had a co-worker blast me for poor and "annoying" naming of classes who then proceeded to rename every class in the frameworks I've created for people here to use.
I'm having trouble explaining my reasoning thoroughly enough for him to accept what I've done as a good approach.
Is what I've done above actually a bad thing? If not, how can I explain otherwise? If so, why?
Comments are asking about namespaces - I know AS3 in this example has what I know to be called a namespace but I'm not sure if this is the same thing or if it can be used as expected.
Given that Actionscript supports namespaces, there is no reason to use prefixes simply to prevent naming clashes. That's what namespaces are for.
Some people like to use namespaces to significy member variables (ie, underscore prefix, or sometimes m_) and that has some merit, but simply for the sake of name clashing no.
It sounds like you don't quite understand what namespacespackages are in AS3.
An example:
//Class1.as
package com.test.someModule { //This is the package/namespace
public class Class1 {...}
}
//Class2.as
package com.test.otherModule {
import com.test.someModule.Class1; //Class1 can be used as "Class1" now. Otherwise you would do "com.test.someModule.Class1"
import com.test.someModule.*; //You can also use the "*" to "import" all classes in that package
}
I have to agree with your co-worker, your class names are 'annoying'.
In Actionscript 3 we use the package name to define the namespace of a class. If you're not sure what namespace means, take the wikipedia definition (as of the time of writing):
"In general, a namespace is a container for a set of identifiers
(names), and allows the disambiguation of homonym identifiers residing
in different namespaces."
So you will never "conflict with class names" as long as you name your packages correctly. Most developers use what is called the reverse domain notation to name their packages (e.g com.mywebsite.MyGenericNamedClass). Domain names are unique so it's very unlikely you would clash with another class.
As a rule of thumb the class name should be as descriptive as possible, so some of your class names will be the same as someone else's class. Take the default Sprite class for instance:
import flash.display.Sprite;
import uk.co.mywebsite.Sprite;
if you then initialize an object:
var mySprite:Sprite = new Sprite();
The compiler would not know which Sprite you want to initialize (is it the flash sprite or your own custom sprite), and it would throw an error.
The solution is simple: because your packages have been named properly, all you need to do is to use the full class name including the package name to initialize your object:
var mySprite:uk.co.mywebsite.Sprite = new uk.co.mywebsite.Sprite();
var myOtherSprite:flash.display.Sprite = new flash.display.Sprite();
Mind you, you would rarely need to do that. This is only necessary if you want to use those two classes (the default Sprite and your own Sprite) in the same scope. Generally, you would only import your own class:
/* we are not importing this any more
import flash.display.Sprite;*/
//only importing my own class
import uk.co.mywebsite.Sprite;
/* now I can initialize my object without using the full class name, and the compiler knows
I mean my own Sprite class */
var mySprite:Sprite = new Sprite();
Rather than use a hard-coded switch statement where you pass it the string name of a class and it then instantiates the appropriate class, I'd like to pass the actual name of the class to my factory method and have it dynamically create an instance of that class. I thought it would be trivial and am surprised it is not working. I must be missing something quite basic:
sample code:
createProduct(50, "Product1Class");
createProduct(5, "Product2Class");
private function createProduct(amount:uint, productClassName:String):void {
var productReference:Class;
try {
productReference = getDefinitionByName(productClassName) as Class;
for (var i:uint = 0; i < amount; i++) {
var product = new productReference() as ProductBaseClass; // throws reference error!
}
} catch (error:ReferenceError) {
throw new ReferenceError(error.message + " Have you linked a library item to this class?");
}
}
The only thing that may be a little odd (not sure) is that these "products" are actually linked Library items (ie: I have a movieClip in the Library that has a linkage to Product1Class and another to Product2Class both of which extend ProductBaseClass, which in turn extends MovieClip.
Why the ReferenceError?
If you have a runtime loaded library then the Class's are not compiled into the main swf, so you get the runtime reference error when you try to create them.
To work around this you can declare "dummy" vars of the classes you want to compile, or if using the flex compiler there are options to include the classes you are missing.
e.g. declare these anywhere in your project
private var p1:Product1Class;
private var p2:Product2Class;
Its a frustrating problem, if your classes extend MovieClip which is a dynamic class you might be able to access the properties etc by doing something like this:
var product:MovieClip = new productReference() as MovieClip;
p1["someCustomProperty"]; //Dot notation might work here as it is a dynamic class
Chris is absolutely right, the ReferenceError is actually being thrown during the call to getDefinitionByName, meaning that the reflection method cannot find Product1Class or Product2Class in your application domain. You can always check if a definition is available by checking the application domain directly, like:
// inside your createProduct method, yields 'false'.
ApplicationDomain.currentDomain.hasDefinition( productClassName );
Are these library assets loaded in at runtime? If so, you can either make sure that the library swf is loaded into the current application domain by adding an appropriately configured LoaderContext to your Loader, or you can replace the call to getDefinitionByName with the loaded swf's application domain's getDefinition method.
getDefinitionByName() and ApplicationDomain.currentDomain.hasDefinition() require full qualified class names. The example code in the original post works when Product1Class and Product2Class are in the default package. However, if you move the product classes to another package, you have to make sure that you are supplying the fully qualified class name to getDefinitionByName().
So if we put our product classes in com.example.products, then the call becomes:
productReference = getDefinitionByName("com.example.products.Product1Class") as Class;
I'm not really sure what the best practice is with this kind of dynamic factory class, but what I ended up doing (since all products were in the same package) was to create a constant within my factory class that defines the package for my products:
private const PRODUCT_PACKAGE:String = "com.example.products."; // note the trailing period
So that way your client code doesn't need to know (nor define) the product package. You just prepend this constant to your product class name when using getDefinitionByName().
I'm used to work in Java, so perhaps this question is a Java-oriented Perl question... anyway, I've created a Person package using Moose.
Now, I would like to add a few subroutines which are "static", that is, they do not refer to a specific Person, but are still closely related to Person package. For example, sub sort_persons gets an array of Person objects.
In Java, I would simply declare such functions as static. But in Perl... what is the common way to do that?
p.s. I think the Perlish terminology for what I'm referring to is "class methods".
There's no such thing as a static method in Perl. Methods that apply to the entire class are conventionally called class methods. These are only distinguished from instance methods by the type of their first argument (which is a package name, not an object). Constructor methods, like new() in most Perl classes, are a common example of class methods.
If you want a particular method to be invoked as a class method only, do something like this:
sub class_method {
my ($class, #args) = #_;
die "class method invoked on object" if ref $class;
# your code
}