What Are Namespaces All About?



I always wondered where I would end up using custom namespaces in ActionScript 3. Now that I’ve been using them I have found a few bugs and gotchas, tips and tricks, and now I generally understand namespaces better (or think I do).

(when reading this article it will help if you already have some familiarity with namespaces in Flash & Flex. To learn more about namespaces awesomeness, John Lindquist has an excellent video post that covers the concepts really well and goes into some advanced topics)

To start with I’d like to present a unique review of namespaces concepts (this isn’t pasted from the documentation, so it might be either 1-more helpful or 2-just plain wrong). There are reportedly 5 types of namespaces, but I’m going to say there are only 4 (this is the helpful/wrong portion).


  • Private – available only to the class that defines it.

    It’s cool to note that private members are not restricted to object instances, just to class scope. This means that one instance of Box can access the private members of another instance of Box, as long as your code is written in the same package/class (the same .AS file more or less).

  • Protected – available only to the class and classes that extend it.
  • Protected members are NOT available to super classes. If an object tries to access its own protected members in a superclass (eg this["mySubProperty"]) you will have a runtime error. Only public (or custom) namespace allows this.

  • Internal – available only to classes in the exact same package.

    Internal members defined in com.xtyler.foo.bar are not available to classes in com.xtyler.foo, or com.xtyler.foo.bar.sub. Because of this restriction I’ve never seen much of a use for the internal namespace … until now (see further down)

The above namespaces are all very unique and are particular to the behavior they embody. The last type of namespace I’d like to call a “named” namespace. Both public and custom namespaces can be available from any other class as long as that class supports the name. When using custom namespaces the name is supported through use namespace my_custom_ns; The public namespace is automatic, as if every class had use namespace public at the top. So custom namespaces can be considered public to any class that wants to know about them. This is seen when you have two members of the same name in one class, you have to label the member explicitly when access it or you will get an error “1000: Ambiguous reference to member.”

public class Component
{
	public var data:Object;
	cust_ns var data:CustomClass;
 
	public function Component()
	{
		public::data = {};
		cust_ns::data = new CustomClass();
	}

And that brings me to why custom namespaces are nice. Why use a custom namespace when it doesn’t really restrict access, when it’s just another version of public? It’s all about the API baby! Keeping it clean and simple so when someone else uses your class they don’t get overloaded with methods and properties they’ll never use, or can’t use.

Ok, so now with all the different tips and tricks and bug workarounds (yes, if you can believe it, Flex & Flash have problems with namespaces)

Namespace Bugs First:

Flex Builder seems to have a tough time admitting that custom namespaces are valuable members of society. You won’t ever get auto-complete for custom namespaces. When using the a custom namespace (especially flash_proxy for some reason), the automatic “Organize Imports” behavior zaps the import … and it runs ever time you code-complete, so you’ll find yourself constantly replacing the import. But add the use namespace flash_proxy; line above your class and you’ll enjoy many hours of organized imports. It’s best to always add this line of code, even if you’re not accessing the members, just defining them.

And another thing, where you add that line of code makes a big difference. This one was pretty frustrating: if your use namespace is inside the class definition, you get various bugs showing themselves through the ASC. Not at first mind you, but as soon as you try and override a custom namespace method, or access one of two members that have the same name but different namespaces, you’ll run into errors such as “Namespace was not found or is not a compile-time constant.” Place the use namespace just outside of your class, inside the package definition.

package com.xtyler.foo
{
	import com.xtyler.foo.bar_ns;
	// here
	use namespace bar_ns;
 
	public class SpaceNamer extends EventDispatcher
	{
		// not here
	// ...

It’s a strange work-around, but it’s a work-around! I could not override a custom namespace for some time until I found that nugget. (thank you to some anonymous tip out there in the comments of a random forum I can’t seem to find again)

Ok, now with the helpful stuff.

  1. mixed namespace getter/setter (I love this one). You sometimes want to allow a property to be retrieved only, not set by other people, but you still need to set it within your own library of code. Note: internal below can be any namespace, including one of your own. This of course can be handled by a method or something else entirely, but it’s nice to be able to interact with the same property.
    public function get commands():Array
    {
    	return _commands;
    }
    internal function set commands(value:Array):void
    {
    	// internal setting to your hearts desire
    }
  2. Nest your namspace in the middle of property resolution. You’ll understand what I’m talking about by the example. Now maybe I’m slower than the rest, but I didn’t know you could do this. I thought the namespace had to proceed the entire line, which doesn’t work for things like my_ns::someObj["prop"] … the compiler thinks you’re trying to target someObj in that namespace and throws an error. Insert your namespace inside evaluation for precise resolution.
    myObj.my_ns::prop;
    // or
    history.internal::commands = [];
  3. That brings me to another one … they’re all namespaces, and so call all be accessed via the namespace operator.
    var cmd:Array = history.public::commands // getter is public
    history.internal::commands = cmd; // setter is internal
  4. Restricted custom namespaces through the use of Internal. This concept is pretty cool but I haven’t used it yet (I might refactor to it). You use this if you really want to hide your members AND their namespace. First it’s important to know that, when defining a namespace you have the option to assign it a string.
    package com.xtyler
    {
    	public namespace xtyler_ns = "http://xtyler.com";
    }

    When you give the namespace a string it can be redefined elsewhere (even under a different name) with that same string … the string becomes the namespace, the the identifier is just a name. So the idea is that you can define an Internal copy of the same namespace in every package and have access to other packages via the custom namespace, but keep the namespace a secret still. It’s not real security, but here it is.

    package com.xtyler.foo
    {
    	internal namespace secret = "https://confidential.xtyler.com";
    }
    package com.xtyler.bar
    {
    	internal namespace secret = "https://confidential.xtyler.com";
    }
    package com.xtyler.foo.sub
    {
    	// can even be a different name inside the package, but can be accessed as a shared namespace between packages
    	internal namespace bigSecret = "https://confidential.xtyler.com";
    }
  5. A manifest.xml file is a great way to automatically give your components their own namespace in MXML. One nice quirk to know about in Flex Builder is that it will use the subdomain of your namespace in its code-completion. So if I want my components to code-complete with xt rather than xtyler, I should define my namespace “http://xt.xtyler.com/2009″ – use whatever other convention you’d like. It would be nice to define this explicitly, but is not currently supported in Flex Builder 3.
    <xt:MyComponent xmlns:xt="http://xt.xtyler.com/2009">
    	<xt:ChildComponent/>
    </xt:MyComponent>
  6. Create a variable of the type Namespace. By defining a property that points to a namespace it can be assigned to any namespace at runtime. This can turn out to be a nice little in-class strategy pattern.
  7. See John’s excellent video post“>video post on namespaces for an example of this last one plus a lot more, seriously.

    Once understood namespaces are a great tool in crafting API’s and making your objects clean and usable for other developers. I hope if you’re working with namespaces in ActionScript 3 you will find these guidelines useful.

    

    2 Responses to “What Are Namespaces All About?”

    1. Quick note:

      Adobe advises against “use namespace”. You should always stick to the “mx_internal::foo()” convention.

      @see http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions

      Do this:

      import mx.core.mx_internal;

      // Later, in some method…
      mx_internal::doSomething();

      Not this:

      import mx.core.mx_internal;
      use namespace mx_internal;

      // Later, in some method…
      doSomething();

    2. xtyler says:

      Thanks John, good to know. When used above the class (in the package) “use namespace” works fine and keeps your import from disappearing. However I still revert to explicit coding using “mx_internal::foo()” to keep ambiguities out. So I don’t really benefit from its intended use :)

    Leave a Reply

  • drugs hair loss
  • antibiotic
  • side effects of antibiotics
  • nexium health
  • new medication for cancer treatment
  • congestive heart failure overview
  • canada cialis generic
  • appetite suppressant
  • pain med without prescription
  • buspar online
  • medication pediatric insomnia
  • very cheap viagra
  • increase womens sex drive
  • lowest price generic viagra
  • buying online viagra
  • cheap alcoholism treatment
  • information on ambien
  • celexa and anxiety
  • lamictal withdrawal
  • celebrex capsules
  • diabetes treatment
  • pain meds no prescription
  • weight loss food
  • body building diets
  • drugs fda
  • anti-fungal
  • pharmacy allegra
  • parkinsons disease medication
  • reducing high blood pressure
  • how does viagra work?
  • medications for depression
  • clomid cycles
  • best male enhancement drugs
  • bodybuilding nutrition buy supplements
  • natural dog health
  • next day medication
  • herbal weight loss products
  • weight loss nutrition
  • famvir dose
  • cheap antibiotics
  • order zoloft
  • zyrtec medication
  • acne skin treatment
  • prescription pain medicines
  • wal mart pharmacy
  • cheap nolvadex
  • online phentermine online prescription
  • tips for insomnia
  • stress medicine for cats
  • canada online drug stores
  • osteoporosis evista
  • viagra order online
  • drugs online no prescription
  • cheap birth control online
  • newest bodybuilding products
  • treating diabetes
  • deep sleep disorder
  • celexa buy
  • how to lose asthma
  • rheumatoid arthritis medications
  • xanax sales
  • high cholesterol diet
  • anxiety order
  • canada pharmacy
  • vitamine guide for dogs
  • different treatments of alcoholism
  • online apotheke
  • hypertension and low heart rate medications
  • treatment for hepatitis c
  • list of blood pressure medicines
  • information on sleeping aids
  • cheap antibiotics
  • bust enlarge
  • how to get viagra prescription
  • muscle nerve pain
  • mens health 40
  • hair re-growth
  • acai berry products
  • tips for gaining muscle mass
  • where to order soma
  • baby acne
  • cialis 10
  • viagra discount online
  • sleeping problems uk
  • buy cialis without a prescription
  • free stop smoking ways
  • womens health menopause
  • how to relieve ear pain
  • hoodia fast
  • aldactone medication
  • uric acid remedies
  • generic zyrtec
  • hangover help
  • buy ambien online cheap
  • lexapro paxil
  • sinus infection med
  • dog lose weight
  • order birth control
  • anti-fungal
  • neck pain
  • psoriasis treatments
  • cialis on line
  • pravastatin
  • new heart attack drugs
  • how to cure diarrhea
  • online pharmacy ratings
  • generic allegra
  • ativan prescription
  • prescription for severe stomach pain
  • medical irritable bowel
  • teeth whitening buy
  • women's hair loss remedie
  • why most people benefit from antidepressants
  • pain cure
  • klonopin anxiety
  • hiv medications
  • prevent itching
  • xanax buy on line
  • nolvadex no prescription
  • xanax perscription
  • anxiety disorder
  • canadian arthritis medication
  • menstrual cramp pain
  • stomach ulcer pain
  • dietary supplement
  • acai berry pills
  • viagra coverage california
  • cures for depression
  • lower your blood pressure
  • treatment of psoriasis
  • cold sores help
  • buy Lozol
  • high blood pressure and treatment
  • pet health care
  • diet supplements distributors
  • cyclophosphamide
  • get klonopin
  • anti-fungal
  • shoulder arthritis
  • cheap caffeine
  • acne tips
  • free prescription medication
  • cat anxiety medicine
  • hepatitis c treatments
  • medication for severe chronic pain
  • order prozac
  • blue pills
  • parkinson's meds
  • anti malaria drugs
  • diet pills online
  • online drug store
  • vascular edema
  • online valium no prescription
  • help stop smoking
  • hydrochlorothiazide generic
  • medication prices
  • cold v flu
  • congestive heart failure med
  • blue pills
  • kidney cancer drugs
  • chlamydia cures
  • vitamin c for dogs
  • oral diabetes medication
  • us drugstore
  • ultimate weight loss
  • list pain meds
  • cialis best on-line drugstore
  • ambien sample
  • new treatment for heart failure
  • pet meds on line
  • buy clomid
  • cheap cialis site
  • bodybuilding nutrition
  • small penis
  • ambien dosages
  • treatments and cures for epilepsy
  • natural weight loss supplements
  • dry skin treatment
  • online order ambien
  • symptoms of stop smoking
  • blood pressure treatment drugs
  • diclofenac dosage
  • helping high blood pressure
  • bronchitis medications
  • antibiotics safe for dogs
  • immune system strengthen
  • best weight loss pills
  • usa pharmacy
  • allied health
  • colon cancer treatment
  • drug treatment for alcoholism
  • tramadol very cheap
  • early prostate cancer treatment
  • side effects claritin
  • retin a cheap
  • online pharmacies in mexico
  • new treatment for allergies
  • prescription drug prices
  • generic plavix
  • buying viagra prescription