Building Framework Independent Code Libraries

I’ve recently encountered a couple of libraries that despite being 99% pure AS3 had minor dependencies on the Flex framework that prevented their use in ActionScript projects or in Flash without modification. This is unfortunate, because it limits the immediate usefulness of the libraries, and fragments the community’s access to them.

Regrettably, this approach is (unintentionally) promoted by Adobe. There is a ton of useful code distributed in the Flex SDK with minor or no dependencies on the framework, and no effort has been made to eliminate those dependencies and distribute / identify those classes for use in non-Flex projects. I’d love to see some kind of identifier / documentation for framework independent code, and have it distributed with Flash as well.

<tangent>Moreso, I’d love to see a core UI framework that is shared between Flash and Flex, and is extended (in the general sense, not necessarily via inheritance) with Flex specific functionality (and the bulk that implies). It’s time for a unified component framework in the Flash platform! But that’s a rant for another post.</tangent>

So, what strategies can you use to create framework independent libraries?

The most obvious approach is to avoid including framework dependencies whenever possible. For instance, use an Array or Vector instead of an ArrayCollection. It’s platform independent, and a lot more efficient. Almost all of the libraries I release use this approach. Of course, this isn’t always possible or desireable, so we need other solutions.

From an architecture standpoint, you can utilize inheritance, interfaces, and composition to append framework specific functionality to your core code.

Inheritance allows you to “branch” your core logic to create framework specific subclasses, including all framework imports. This comes with all the usual caveats of inheritance, including making sure you define methods appropriately to make it easy to override ones that will become framework specific. Generally you will have a functional core class to use in ActionScript projects, a Flex specific subclass, and potentially a Flash specific subclass.

Composition can provide a more flexible approach. You can build your core classes to rely on plugins that encapsulate all framework specific logic, and which define a simple interface. By default these plugins can point to a framework independent implementation (even to the classes that use them). As a simple example, you could have an ITextInputMediator plugin that exposes methods and events for working with text inputs. By default it would point to a TextFieldMediator class, but could also be pointed at a FlashTextInputMediator or FlexTextInputMediator classes.

The act of setting up these plugins could be done manually by the library user, or could use a keystone class. This class would be compiled into a project once, and would import and assign the appropriate plugins and factories when it initializes.

You can also use conditional compilation to toggle imports and logic blocks based on the environment. For the most part, this offers the cleanest approach, but you must ensure to document it clearly, as conditional compilation is not yet widely used or understood in the Flash world.

Locally, you can leverage reflection (ex. getDefinitionByName and the “in” keyword), dynamic access, and events to your benefit. The first two should be used as little as possible, because they come with unwanted side effects like reduced compile time error checking. Because the event model exists at the player level, you can listen to any event from any IEventDispatcher object, without having to reference its type directly. SPL uses this to listen for “valueCommit” events from Flex controls, without having to import the framework – it uses a local constant for the event name instead of importing the Flex event object.

As a last resort, if your library has dependencies on well encapsulated Flex framework classes (ex. utility classes like HashUtil), you could choose to distribute them with your library to make it easier for users to get running. Always test the package in isolation to ensure you have included all of the dependencies (like that pesky Version.as file), and document which classes you included, so people using your library with Flex can optionally delete the copies you included.

Making your libraries more widely usable means they can be used by more people, which is really the point to releasing them. It also helps provide a more consistent code base for all Flash platform developers, regardless of the framework they’re using. If you aren’t going to make your library framework independent, at least consider trying to architect it in such a way that another developer could more easily modify it to work without the dependencies.

Now let’s see what we can do about encouraging Adobe to embrace this idea internally. 🙂

If you have other approaches or ideas on creating platform independent libraries, feel free to share in the comments.

Silverlight, MIX & gskinner.com

As some people have noticed, I will be speaking at Microsoft MIX this year. I’m sure a few people are curious what I’m doing there.

A couple of months ago, gskinner.com was presented with an opportunity to work on a very interesting Silverlight project, with a fairly flexible timeline. I’ve been looking for an excuse to dig deeper into Silverlight for a while so it made a lot of sense. As an extension of that project Microsoft asked me to present a talk at MIX discussing the project. Regrettably, the project start was pushed back due to (not entirely unexpected) bureaucratic delays. As such, the talk will focus on a more general overview of the casual gaming market, and what opportunities exist in it for Silverlight.

That covers why I’m speaking in Vegas, but what about the politics? While I am not so naive to believe that there are no politics involved with asking me to speak (though MS assures me there are not), I am choosing not to be concerned with them. The opportunity that was presented to us was a good one – it’s a fun project, it made business sense, and it provided us with a low stress environment to really learn Silverlight development.

While my primary focus is (and remains) Flash, I am an interactive developer. I would be sorely remiss to ignore other technologies. Not only does knowledge of other technologies potentially open new project opportunities, but it lets me reinvest ideas and mental models from them back into my work with Flash. Working with C# has already sparked some new ideas for me (not to mention a few AS3 feature requests). Knowledge of alternative technologies also lets us suggest the best possible solutions for our customers or talk them out of a bad one.

We have done HTML/AJAX work in the past and continue to do small amounts of iPhone development for these same reasons. As HTML 5 matures, you can bet we will play and work with it to see how it fits (or doesn’t fit) into our offerings.

We are not jumping ship to Silverlight. Microsoft has not “bought” our loyalty, and they have assured me that working with us is more about seeing what we can do with their technology and our experience in interactive than as a political move. You’ll note that at no point do they associate me with Flash (though it is obviously somewhat implicit), and I will be minimizing comparisons between the technologies when I speak.

I’m looking forward to the conference. I’m a little hesitant with regard to my talk, because I don’t feel I’ve played with Silverlight enough to really discuss the details I’d like, but I’m excited to see what Microsoft announces, and to hang out with the community. If you’re going to be in Vegas for the event look me up!

I’m planning to blog a fair amount about my experience with Silverlight on this project, once I feel that I’ve dug deep enough to be fair. I’ll be very blunt and honest in what I find – it’s one of the risks Microsoft is taking in involving me, but also shows a level of confidence with the new version that I haven’t seen in the past.

Let me know if you have any questions, and I’m happy to answer them in the comments.


UPDATE: I just want to clarify the intent of this post. It’s not intended as a defence of working with Silverlight – I don’t believe one is necessary. I haven’t met with any hostility, but there has been a fair amount of curiousity, so I thought I would provide some information for those that were interested.

ASDocr Update for AIR 2 Beta 2

ASDocr 1.1 is available. This update provides compatibility with AIR 2 beta 2, fixes a bug that prevented multiple exclude-namespaces values from working, fixes a problem with locating the default output directory on OSX, and correctly opens the last used configuration when you restart the application.

ASDocr provides a GUI for working with ASDoc to make generating documentation for AS3 classes easy. For more information on ASDocr, read the original post on it.

To install version 1.1:

1. Uninstall ASDocr version 1.0

2. Upgrade to the AIR 2 beta 2 runtime. It can be found here.

3. Download and install ASDocr 1.1

Known issues:

There is a bug in AIR 2 beta 2 that can cause the Open HTML and Open Output Folder actions to take a long time (~30s) on some Windows XP machines.

Download:

Download for Mac OSX

Download for Windows


UPDATE: The latest version of ASDocr, with support for the AIR 2 Release Candidate can be downloaded here.

Create New Files & Projects In OSX Finder Easily

QuickFiles is a free OSX 10.6 AppleScript service plugin that lets you create new files of any kind in the Finder with a keystroke. Install QuickFiles then place files or folders that you’d like to use as templates into the “QuickFiles Templates” folder. When you run QuickFiles, simply select a template from the list, and it will be copied into your current folder.

QuickFiles also supports multi-select, so you can create two or more files in one operation. Just hold Command or Shift to select multiple templates from the list.

Best of all, everything can be controlled via the keyboard by binding a shortcut to the service (I used Command-Control-N). Hit the keyboard shortcut, type the first letter or two of the template you want, then hit enter to copy it into your current folder. The new file is selected for you, so you can immediately hit Enter to rename it, or Cmd-O to open it for editing.

I originally created QuickFiles because I was jealous of Window’s right-click menu to create new files in Explorer, but I think it’s evolved into something much more powerful and usable.

Here’s a few ways you can use it:

  • create a new blank text document
  • create a new class file, FLA, or xml file from a template file
  • create a copy of a sales letter or contract that you personalize often
  • create a new project folder with all of its sub folders and starting files already in place
  • create an alias to a file or folder that you use regularly
  • copy frequently used code libraries (including package directories) into your project

This version is only compatible with OSX 10.6 Snow Leopard. There is an older version available here, with less features, that supports early versions of OSX.

You can download QuickFiles for OSX 10.6 here. It includes the AppleScript workflow service file, and a ReadMe file that I highly recommend reading for information on installation, use, and setting up a keyboard shortcut (all very simple, not necessarily self-evident if you haven’t installed services before).

I’ve found this plugin very useful for coding, and day to day tasks. Hopefully it’s useful to other people as well.

My Thoughts on the Future of Flash

Since the iPad’s release, it’s been nearly impossible to avoid debates (and more often, flame-wars) about Flash, its flaws, and its future (or lack thereof).

Honestly, I’m pretty sick of the discussion. Early on, I wrote up a huge article dealing with the most common themes, misconceptions, and outright lies that were circulating, but refrained from posting it. Since then people have asked me to share my thoughts, and I’ve decided that for the sake of those just getting started with Flash I’d talk about it a little.

Let me start by saying that I completely lack empathy for people who get so emotional about technology. I don’t care if it’s Mac vs. PC, XBox vs. PS3, or Flash vs. HTML 5, I say use whatever works for you. If you want to get into a mature discussion about it’s pros and cons, that’s cool, but spouting vitriol on a public forum just makes you look like an ass. Period.

If you hate Flash so much, turn it off or install a blocking plugin. It won’t bother me in the least. If enough people do it, it will start to show up in the plugin stats, and the industry will move away from it. But please, avoid spouting crass, ignorant FUD trying to justify your choice.

Sure, I make my living off of Flash, but I consider myself an interactive developer, not a Flash developer. I love working with Flash, and think it has a long life ahead of it, but even if it went the way of VRML tomorrow, working with it has given me an understanding of rich interactive content development that’s difficult or impossible to gain in any other technology.

This skill set is applicable to so many things: WPF on Windows, Cocoa development on Mac / iPhone (ex. Core Animation), Silverlight, mobile development, and of course the emerging HTML 5 standard. Languages are easy to learn – mental models, process, and the experience gained from years of working with rich interactive are a whole lot harder.

I’ve been working with Flash for over 10 years. I do it because I love it. It’s far from perfect, but there’s no other technology that offers access to such a broad range of interesting projects with such a low barrier to entry. I’ve worked on rich applications, experimental “art”, marketing sites, games, mobile projects, installations, computer vision, and even a couple of banner ads. I love what Flash allows me to do, but I’m not married to it. I have no problem recommending, or using another technology if I think it’s a better fit for a project.

Considered rationally, the absolute worst case scenario for Flash player is that its core feature set is replaced by HTML5 (canvas, video, etc.) over the course of the next 3-5 years. Even if things go miraculously well, these standards are not going to be implemented consistently across major browsers and devices, then adopted by the general public faster than that.

In this worst case scenario, there will be a slow decline in work available to Flash developers over the course of a decade or so, offering plenty of time to apply your skills to another technology.

In the more likely scenario, HTML5 will slowly overcome the obstacles facing its adoption (ex. Codecs, IE), and begin providing an alternative to Flash for many scenarios. For example:

  • A fair amount of video will eventually be delivered with the video tag, though the lack of advanced features (content protection, variable streaming, etc) means it will won’t replace Flash completely. This in itself will keep the plugin fairly ubiquitous. Example.
  • You’ll see some very impressive apps created with HTML5, though they will require significantly more effort to build because of the less robust tools and language. Example.
  • You’ll see some interesting games and interactive experiences built with it, but it will remain much easier to design and code these experiences with Flash. Also, people will start to realize that along with the capabilities of Flash, you also get some of the drawbacks, like high CPU usage and occasional crashes. Example 1. Example 2.

Flash will continue to evolve, optimize, and add new capabilities. With some exceptions (namely anything beginning with an “i”), it will continue to provide a more consistent environment for deploying rich experiences to multiple platforms.

In short, I’m not worried about the future of Flash. I can’t predict what it will be in 5 years, but nobody can. If the naysayers are right, and it becomes obsolete, that’s fine, I’ll move on to something else. In that case, maybe Adobe will even rejig their tools to output to HTML/canvas instead of SWF. After all, they make their money selling those tools. The Flash player is an expensive loss leader.

If they’re wrong, I’ll likely still be cranking out cool stuff with Flash. However, as a smart developer and responsible business owner, I will continue playing with HTML5 and watching its evolution, just as I’ve done with AJAX, iPhone development, and Silverlight. Eventually we’ll probably offer HTML5 development in addition to our current services.

Finally, I want to address all of the hate and insults that have been directed at the Adobe engineers. Yes, Flash player crashes. Yes, its performance could be better. But the Flash player engineers are some of the smartest, most passionate and dedicated professionals I’ve had the pleasure of working with.

Try building a player that runs a huge range of dynamic content written on a variety of tools (some of which you don’t control) by developers with massively varying skill levels. Now try making it compatible, consistent, and performant across dozens of OSes, browsers, platforms, and devices. And maintain backwards compatibility with the last 9 versions even while your target platforms change. And keep it under 5MB. And maintain it in parity with an OSS effort (Tamarin). And try to keep up with the demands of one of the most active and vocal developer communities.

Trust me, it’s harder than it sounds (and it sounds pretty damn hard to me). These guys deserve our respect and appreciation. Complain about the player – hell, I want it to run faster, never crash, use less memory, and play video better on Mac – but don’t insult the people working on it.

I have so much more to say, but I’d largely just be repeating things that have been repeated ad nauseam, so I’ll end here.

I happily welcome your thoughts and comments, however I refuse to let things degenerate into the name-calling, ignorance spouting, poo-flinging mess that it has on other sites. As such, contrary to my usual policy, I will aggressively delete posts that are not respectful and on-point.

PerformanceTest v2 Beta: Benchmark AS3 / Graphics

When I built the original PerformanceTest, I hacked it together quickly to meet a specific need I had at the time. As I used it, I found I needed more capability, and I became increasingly frustrated with both the messy code, and the poorly thought out API.

In response to feedback, and my own frustrations, I’ve completely rebuilt PerformanceTest to be more robust, extensible, feature-rich, *and* easier to use.

Core features:

  • Track time, memory usage and retained (unreleased) memory for functions.
  • Test rendering time for any display object.
  • Write simple one line tests, or build formal test suites.
  • Test suites can be built using inheritance or aggregation/composition.
  • Trace simple text results, or access robust XML reports.
  • Save XML and compare results between different versions of your code, or on different Flash players.
  • Easily build logging classes to analyze or visualize results.
  • Run multiple iterations of tests to get min, max, and deviation values.
  • Run tests synchronously, or queue them to run them asynchronously.
  • Listen for events from tests, test suites, and PerformanceTest.
  • Integrates easily with TDD by facilitating the creation of tests for time, memory, and retained memory limits.

Here’s a very simple demo:

Continue reading →

A Complete Guide to Using Namespaces In AS3

I need to define a custom namespace in AS3 a couple times a year at most, and nearly every time, I forget how to do it. The docs tell you to use the “namespace” keyword (which I remember), but not where or how to use it (which is what I forget), and google isn’t much help. I always wind up opening mx_internal.as in the Flex SDK as a reference.

With that in mind, here’s a complete guide to using namespaces in AS3. Note that it is about access namespaces, not XML namespaces. Hopefully it saves other devs a few minutes of searching.


What are custom namespaces?

Namespaces allow you to control the access to the members (properties and methods) of a class. You are probably familiar with native access modifiers like public, protected, internal, and private. Custom namespaces allow you to define your own access rules.


What can I use namespaces for?

While there are a range of uses for custom namespaces, three stand out to me as most common:

1. Documenting special conditions for member access. For example, in an evolving API, you may be required to expose methods that aren’t stable. You could place them in a custom namespace (ex. “transitional”), and document it to warn developers that these methods are subject to change. It’s sort of like a EULA for APIs.

2. Providing custom access domains. Namespaces cannot enforce custom access rules (only extend the native access modifiers), but they can provide a way to segregate an API for different user types. For example, you could provide a public API for a library for most users, and an extended API for plugin developers that uses a custom namespace (ex. “plugin”).

As another example of both #1 & 2, Adobe uses the mx_internal namespace to expose methods that need to be accessed widely within the Flex framework, but aren’t meant to be utilized publicly. They document that this namespace is unsupported and subject to change. It has the side benefit of providing hooks for advanced developers that require deep access to the framework and are willing to risk future compatibility problems.

3. Preventing name collisions. You can define members that have the same names in different namespaces. This is particularly handy for dynamic objects. ActionScript 3 uses this for the Proxy object, isolating it’s built in methods in the flash_proxy namespace, so that they are accessible externally, but don’t collide with any user defined methods.


Defining namespaces.

Defining namespaces is easy, just use the “namespace” keyword.

public namespace my_namespace_name;
public namespace my_other_namespace = "uri";

You can create your namespace within any existing namespace, including the built in namespaces (public, private, et al), but you will usually just make it public.

The name can be whatever you want (except reserved words). The naming convention for namespaces is all-lowercase, with words separated by underscores.

The uri is optional, but helps prevent naming conflicts in the case that someone else uses the same namespace name. This should point to a relevant uri, which ideally hosts some brief information on the namespace (though this is unnecessary). For example, Adobe points to http://www.adobe.com/2006/flex/mx/internal for mx_internal, but doesn’t actually host any content there.


Where do you define namespaces?

You can define namespaces in two places – within a class, or in a separate file. I haven’t been able to come up with a real use case for the former, so we’ll focus on the latter. Simply create a new file with the same name as your namespace inside the appropriate package path, and define the namespace in a package declaration:

// in com/gskinner/utils/my_namespace.as
package com.gskinner.utils {
public namespace my_namespace = "http://gskinner.com/as/namespaces/utils/my_namespace";
}


Using namespaces.

First, you need to import your namespace.

import com.gskinner.utils.my_namespace;

You can now use your namespace in the same way as the built-in namespaces. So instead of specifying a var or function as public or protected, you use your namespace.

my_namespace var myProperty:Number=-1;

To access class members within a namespace, you import the namespace, and then you use the whacky double-colon namespace syntax to access properties inside it.

import com.gskinner.utils.my_namespace;
trace(myDemo.my_namespace::myProperty); // traces -1.

You can also “use” a namespace, which opens it within the current scope (class or method), and provides access without the namespace qualifier. This approach requires less typing when accessing a number of members in a namespace, but it makes the code more ambiguous (are you accessing a public method, or one in the open namespace?).

import com.gskinner.utils.my_namespace;
use namespace my_namespace;
trace(myDemo.myProperty); // traces -1.

Got anything to add? Let me know in the comments.

Comment Blocks That Are Easy to Toggle On/Off

Sometimes when you’re coding, you find yourself toggling a block of code on or off by commenting it. Most development environments make this pretty easy with a button or shortcut that will comment or uncomment a selected block.

However, it can be handy to know that there’s a way to achieve the same thing by setting up your block comments in such a way that they can be enabled or disabled by adding or removing a single “/”.

Here’s how it looks with the code commented out:

/*
thisIsCodeIWant.toToggle(onOff);
andMoreCodeHere();
//*/

You can uncomment the code block by adding a “/” at the start of the block comment like so:

//*
thisIsCodeIWant.toToggle(onOff);
andMoreCodeHere();
//*/

After I posted this, hbb reminded me of a related commenting trick. With the following set-up you can toggle between two code blocks by adding a “/”.

//*
thisIsCodeBlock(1);
moreCode();
/*/
thisIsCodeBlock(2);
andMore();
//*/

Just remove the “/” at the beginning of the first block comment to swap code blocks.

/*
thisIsCodeBlock(1);
moreCode();
/*/
thisIsCodeBlock(2);
andMore();
//*/

This is a pretty basic tip, but I’ve found that not all developers are aware of it, so I thought it couldn’t hurt to share it.