Some Controversy over ECMAScript 4

by Josh Tynjala

Last week, I presented a first look at ECMAScript 4, the standard that Adobe uses as a basis for ActionScript. What I hadn’t yet discovered when I posted is that ES4 has caused a bit of controversy among the wider web developer community. We developers on the Flash side don’t always stay in touch with the developers using JavaScript, so I thought I’d highlight some of the arguments and conversations.

Some prominent JavaScript developers, including Douglas Crockford (creator of JSON and a fellow Yahoo) and some folks from Microsoft, believe that the changes in ES4 are too drastic and don’t address problems that should have been fixed. Douglas points out that JavaScript is inherently unsafe, and he argues that ES4 does nothing to fix the security risks. Another common argument is that nothing proposed in ES4 adds functionality that couldn’t be done in the previous version. In short, what’s more important? New functionality that wasn’t available before or better syntax for existing functionality?

The new syntax makes ECMAScript more like traditional programming languages, but the language also aims to stay backwards compatible with the current version. In other words, you can build classes using the new class syntax or you may use prototype like JS developers do today (sort of like how AS1 and AS2 gave us these same options in Flash for a long time). It raises a question in many minds, “Why?”.

The web may face an ugly transition involving widely different coding styles, and poor support for the new syntax across browsers. After almost a decade, developers encounter many differences across implementations of the current version of JavaScript. With so many new syntax options, bugs may cause heavy incompatibilities among early implementations of the new version. While the previously-mentioned version transition in ActionScript was mostly smooth, the browser world has a very different ecosystem that could make widespread adoption of the syntax changes more difficult.

Links

An interesting discussion overall. I’ll be watching with fascination to see what happens to “the language of the web” over the next year. Do I expect major changes to ES4 that could affect the next updates to ActionScript? Not particularly, but the desire for a language that stays true to JavaScript’s current version is strong among those that oppose ES4. I can’t say whether another JS-like language will be proposed as an alternative to ES4, but it’s certainly a possibility. I’m curious to see what happens.

Update: New information about this topic is available in my article How will ECMAScript “Harmony” affect ActionScript 3.

Discover ECMAScript 4: The Future of ActionScript

by Josh Tynjala

Update: Since I wrote this article, some interesting news has surfaced. New information about this topic is available in my articles Some controversy over ECMAScript 4 and How will ECMAScript “Harmony” affect ActionScript 3.

The ECMAScript working group recently released a (PDF) work-in-progress overview of ECMAScript 4. What is ECMAScript? According to the official website, the working group calls it “the language of the web”. More specifically, it’s the basis for languages such as JavaScript and Flash’s own ActionScript.

The official release of ES4 won’t happen until Fall 2008, but the working group releases updates from time to time to keep us informed (or salivating, depending on your level of geekiness). Adobe, a member of the working group, used an earlier draft of ES4 as the basis for AS3, and they’re “publically committed to sticking to [the ES4] standard” (source). The current update to ES4 includes many changes that we will probably see in a future revision to Flash’s programming language. I read the entire document from beginning to end, and I wanted to share some of my favorite discoveries.

Core Classes

Object and Array have picked up some new friends. In particular, a class called Map works a lot like Object, but it allows you to use any value as a key (not just a String). This is very similar to flash.utils.Dictionary in AS3, but there’s one interesting addition that I’ll get to in a moment. Similar to Array, there’s a new class named Vector. Of note, it provides bounds checking, and you can optionally specify a fixed length. Using a new language feature, both Map and Vector are parameterized types. Vector is actually what some might consider a typed Array. When you create an instance, you must specify the datatype of the objects you intend to place inside the Vector. Similarly, to use Map, you must specify both the key datatype and the value datatype. An example borrowed from the PDF overview should help illustrate how these will work:

//create a Map with keys of type * (known as any type) and values of type int
var example1:Map = new Map.<*,int>;

//create a Vector to contain integers
var example2:Vector = new Vector;

Language Features

Some of the coolest additions to ES4, in my opinion, are record types and the like keyword. Think of record types as ultra-light classes. They define members, but aren’t an entire class definition. Here’s an example of a record type:

type Point = { x:Number, y:Number };

It should be no surprise that you can create new instances of these types (you’ll get a regular Object, though) like any class.

var myPoint:Object = new Point();

What’s more interesting is that you can use the like keyword with record types to produce some interesting results. In AS3, a MovieClip has x and y properties that are both instances of class Number. This makes a MovieClip like the Point type described above (don’t confuse it with flash.geom.Point).

var clip:MovieClip = new MovieClip();
clip like Point //true

Imagine being able to run a function on any object that has x and y properties without requiring a special interface or setting a parameter’s type to Object (where you’d have to do runtime checks to ensure that x and y even exist!).

Another useful class-like feature is something called a union type. To understand union types, think of a current feature of AS3: Number, uint, and int are all pretty much interchangeable. That’s because ES4 defines an internal union type AnyNumber to accept and convert all numeric values as needed (notice a few new numeric types, by the way).

type AnyNumber = (byte,int,uint,double,decimal,Number);

The new let keyword gives us a more familiar block scoping mode used by other languages. In the current incarnation of AS3, a variable in a function is always accessible from anywhere in that function, by using let instead of var, you can make a variable that is only in the scope of a for-loop or an if statement. Excellent.

A feature I see requested often is operator overloading. Thankfully, this will be made possible thanks to another new feature generic functions. These functions are outside of classes and they’re pretty close to the bare metal of the runtime. Here’s an example:

generic intrinsic function + ( a:String, b:MyCustomString )
{
    //some operation that concats a MyCustomString with a regular String
}

The docs say that you cannot override a generic operator that has been implemented already, but you can add new ones that support your own custom classes. I’m sure some folks might complain, but I’d say it’s good enough for me. I’d hate to see the messes some dumb developer could create if he changed the way the core types behave with operators.

Finally, I’d like to share iterators. Two new types, IterableType and IteratorType give you the ability to code your classes to work with for-in and for-each-in loops more easily. Previously, in AS3, developers could only iterate over dynamic properties with these loop types. Now, by implementing a couple methods, get() and next() you can give a little more power to your applications, but only if needed. Older AVM1-era Flash applications could always iterate over properties, but today, that’s been removed for a performance boost. Nice to see this feature come back, if a developer chooses to use it.

That certainly isn’t everything new that we’ll see coming in the final version of ES4. I just picked out a few particular things that caught my eye and seemed the coolest. Be sure to read the ECMAScript 4 Overview PDF for full details.

Just as I was “impatiently waiting for ActionScript 3” back in the alpha days, you can bet that I’m just as excited for the next version today. Too bad it could be years away! When? Who knows. I’d say I’m pretty safe guessing that Flash Player 10 is out of the question. Adobe has their hands full with the features they’ve shared already. Furthermore, they would be silly to introduce major language revisions in two consecutive player versions. I’m also still seeing many learning the migration path from AS2, and I don’t think that dangerous sea will calm for a while. Definitely FP11 at the earliest, and after the ES4 spec has been finalized. In other words, be patient, but smile and dream of the cool coding tricks you’ll be able to do someday.

An Open Letter to Silicon Valley Recruiters

by Josh Tynjala

Dear Recruiter,

It looks like you’re helping a hot new client that needs talented developers yesterday. That’s great! Get out there and find the best of the best! I should warn you about something, though. When you want to contact me about the next “YouTube meets Salesforce meets The Next Big Thing™” startup, I may be a little difficult to deal with. It can be boiled down to the fact that I, like many developers, simply don’t like talking to recruiters. We just want to talk tech and write great code, and a recruiter isn’t always the person with the information we need. Adding a middleman to any process sucks. Let me give you some guidelines for keeping things running smoothly when dealing with a stubborn developer like me.

  1. Get to the point. I actually don’t particularly care who’s funding your startup. Investors don’t impress me. Buzzwords force me to read between the lines, so try leave those out as best you can. Honestly, I mostly care about what sort of cool projects I’ll get to work on and if I’ll be able to face interesting challenges. Tell me that you want a Flash or Flex developer, and give me some details about what I could be working on to actually get my attention. Informing me that some company is “the hottest new video startup” doesn’t help me because half the new startups out there call themselves “the hottest new video startup”. I shouldn’t need to ask, “what do they do with video?” In short, if you can’t tell me about the awesome products or services I’ll be able to help build, I’m not interested.

  2. I have contact me links all over my blog. That’s the best means of sending me a message if I don’t know you. I set it up mainly for folks that want to send me questions about my open source projects or blog content, but it’s great for contacting me about anything else too. Messages sent from the contact page go directly to my email inbox. In fact, I’ll admit that I like getting email that isn’t from the zillion mailing lists to which I’m subscribed. Send me something there, and I’ll probably read it. The only recruiter that’s ever gotten me to change jobs started the conversation by sending me a message through my contact page.

  3. LinkedIn messages are okay too. However, I’m unlikely to add you as a connection, even if I send you a response. If I added every recruiter that contacted me, I’d have expanded my network to a useless eighteen billion people that I don’t know very well. My LinkedIn connections are almost always people I’ve worked with or met at professional developer community events. Unless you’ve had a drink with me and talked tech, you’re probably not getting on that list.

  4. Facebook messages are never okay. My profile on Facebook is for personal friends only. Your message will never get a reply on Facebook. Guaranteed.

  5. Are you an employee of the company you recruit for? That’s better than if you work for some third-party recruiting company, in my eyes. Many recruiters don’t necessarily have enough information to interest me, and if you work for the company in question, you’ll be able to put me in contact much more easily with a person who has real answers. If you only have a basic job description, do you really expect me to go out of my way to learn more? I’m already happy with my current employer, so if I’m faced with too many steps to get from a recruiter to useful information, there’s no point in trying.

  6. I’m a Flash and Flex developer. My resume has been known to list a few other technologies I’ve been capable of using, but I believe that I’ve made it extremely obvious that I dig the Adobe Flash Platform above all else. Don’t contact me about your company that wants to build AJAX RIAs. While I am proficient with some JavaScript libraries like jQuery or YUI, I’m not going to drop Flash any time soon. Definitely don’t contact me about server-side development because that’s never going to happen. I’m a front-end, client-side developer.

  7. Do you prefer to contact me by phone? Please don’t. You’re interrupting me while I’m working, and you’re using up my precious time. I will do everything in my power to say, “thank you, but I’m not interested” as soon as possible. With email, I can read your sales pitch whenever I want, but the phone requires me to put everything aside specifically for you, yet another random recruiter. If you must insist on calling me, please see the following suggestions:

    • Don’t call me at work. Do you really think I want to say, “Sure, I’d love to work somewhere else!” when my manager sits nearby? Even giving you my email address (or a better time to call) feels impolite to my current employer. Why put me in a negative situation? It will only hurt your efforts. On a related note, calling the front desk of the company I work for to get my number only impressed me once. I thought the guy was being resourceful. Then I realized that apparently every recruiter does that. Thanks for wasting my employer’s resources too.

    • Don’t leave a voicemail if I’m not here. I’ve had phones that won’t let me delete messages until they’re finished playing. As you can probably probably imagine, I’m going to zone out once I hear, “Hi Josh, I’m a recruiter from [insert some recruiting company]“. I’ll read email or something while I wait for you to finish droning on and on about the boring life stories of your startup’s founders and investors.

    • Don’t ask me for additional contact information over the phone. The spelling of my email address seems to be difficult to understand sometimes. You got my phone number already with your dark recruiter magicks. I’ll bet you can find my email address too. Of course, for best results, consider using my contact page.

In conclusion, Mister or Miss Recruiter, please keep the interruptions of my day to a minimum, get to the point as quickly as possible, and try give me the juicy details. I promise I’m not actually that difficult to deal with. All I ask is that you have respect for my time and needs as an innovative technologist. If you have a job or contract that seems fascinating and stimulating, I’ll happily listen.

Create a pseudo-class from a runtime-loaded image in AS3

by Josh Tynjala

Recently, I’ve been hacking at low-level AS3 features to try to find a way to load an external image and make a class out of it. Basically, I want to create multiple instances of that image using only the new operator. The image path isn’t known until runtime, so I’d like to make a special Loader subclass that knows the correct image path to load before it gets instantiated. As you can imagine, that’s not the easiest requirement to meet.

Screenshot of application built with the method described below
Example Application (View Source Enabled)

A short time ago, Ben Stucki created a class to load external images as icons for Flex components. It’s a very clever solution. He uses a Dictionary to associate the image path with the intended parent. I wish I could have used it, but the class I’m trying to create needs to be instantiated somewhere that I can’t access the parent. Like I said, the class itself really needs to know the correct image URL to load. In AS2, it wouldn’t be too difficult to accomplish. You can hack __proto__ in AS2 to do some interesting runtime subclassing to make a unique class for every URL. Unfortunately, Adobe locked things down a bit in AS3 (for performance reasons, mostly), and __proto__ is no longer accessible to developers.

That said, let’s try to remember back even further, to our AS1 days, when true classes didn’t exist. Classes were function objects, and we added member variables and methods through prototype. Thankfully, class-like functions through prototype are still possible in AS3. Consider the following code:

var MyImageClass:Function = function():Loader
{
	//we need a Loader that automatically loads our image
	var loader:Loader = new Loader();

	//the URL will come from the prototype
	loader.load(new URLRequest(this.url));

	//our "constructor" returns the Loader!
	return loader;
};

//the image to load in our dynamically created "class"
MyImageClass.prototype.url = "yahoo_logo.gif";

This creates a constructor-like function that returns an instance of Loader. This loader automatically loads an image URL that we place in the function’s prototype. If you’re using Flex, you could easily modify this function to make it return a SWFLoader instead.

Usage is surprisingly simple. We pretend MyImageClass is a real class, and our friend the new operator takes care of everything.

//add two images to the display list
var image1:Loader = new MyImageClass();
this.addChild(image1);

var image2:Loader = new MyImageClass();
this.addChild(image2);

Two images will automatically load. That’s perfect!

…well, sadly, it’s not perfect. There’s some bad news. I had hoped this would be able to replace Ben’s code in Flex too, but I quickly discovered that while this special pseudo-class (as I now call it) behaves like a real class, Flash Player knows that it isn’t a real Class. For example, the icon style on the Button component in Flex expects a Class object. Our pseudo-class is actually a Function object, and these two types are not compatible. Flash Player will throw a runtime error if I try to set this style to a Function.

Thankfully, I need these pseudo-classes for a component that I built myself. I can ensure that I type my variables correctly (or at least branch depending on the type) so that both Class and Function can be used. As much as I’d like to be able to use these pseudo-classes for icon and skin styles in Flex, that’s just not in the cards.

If you’re interested, I built a utility class called LoaderUtil with a function createAutoLoader() that encapsulates this functionality into a simple function where you pass an image URL, and an optional LoaderContext (for tweaking cross-domain options and other stuff on the Loader), and you receive one of these pseudo-classes back.

"ActionScript 3.0 Design Patterns" a good place to start for Flash developers

by Josh Tynjala

If you’re looking to improve your coding practices, and earn that “Engineer” part of your title, design patterns are a good thing to know. I recently picked up a copy of ActionScript 3.0 Design Patterns by William Sanders and Chandima Cumaranatunge. With Flash 9 bringing more developer-friendly improvements to ActionScript, and Flex making waves in the technology world, now’s a great time to become a better developer. I know a few design patterns well, but I know that I have many more to learn. If you’re unfamiliar, design patterns offer recognized and accepted solutions to the common project requirements. This book, we’ll call it AS3DP for short, gives a good foundation for a growing developer.

AS3DP is divided into several sections based on a basic categorization of design patterns. These categories have been defined previously in other important texts about design patterns, and I’m glad that the authors chose to stick with the precedent. They appear as follows.

  1. Creational patterns

  2. Structural patterns

  3. Behavioral patterns

  4. Multiple patterns (more than one pattern combined into one)

The section on Creational patterns starts with the Factory Method pattern. This pattern is explained very well with two interesting examples. The first example, a Print Shop, helped me understand the problem and solution very easily, and the second example, a shooter game, was a fun way to reinforce the knowledge. Next, the Singleton pattern is introduced. This pattern is an obvious choice, as one of the more common ones I’ve seen mentioned by ActionScript developers, and the section includes good material.

We go next into Structural patterns. I found the Decorator pattern, again, very easy to understand. The examples in this section illustrated the purpose well, but they didn’t quite catch my interest as the ones in previous chapters. Paper dolls probably won’t appeal to the average target reader of AS3DP. Decorating with “Deadly Sins and Heavenly Virtues” seemed weird too. I would have preferred the focus to have been closer to real-world projects as much as possible. The Adapter pattern is another well-explained pattern. The example of easily controlling a car in different ways (such as through code or the mouse) brought my interest back a bit. This section ends with the Composite pattern which is explained through the Flash display list (an excellent choice to help the reader’s understanding) and inverse kinematics, another interesting topic.

The third category of patterns features Behavioral patterns. We start with the Command pattern. One example implements undo, and another sets up controls for a podcast media player. Much to my annoyance, the authors decided to include the Observer pattern. Considering that they don’t have an exhaustive list of the classic patterns in this book as it is, I don’t understand why they decided this one is important to include. One of the native classes in Flash Player, EventDispatcher, already uses this pattern. To be blunt, very few developers will ever implement the Observer pattern in AS3. The Template Method pattern was easy to understand, and the examples summed it up well. Overall, he State pattern was introduced very well and I found it understandable. The video player example could have used a little more work, I think. I understand that simplicity is important for examples, but something felt strange about a video player that couldn’t go directly from a paused state to a stopped state. Behavioral patterns end with a look at the Strategy pattern.

The final category of design patterns introduced in AS3DP is the set of patterns that combine multiple patterns into one. The first is Model-View-Controller, or MVC for short. Along with Singleton, this is one of the most common patterns that seems to appear in ActionScript code. The examples for this one were generally interesting, and it was a good review for me. The finally pattern is Symmetric Proxy. It seemed to be explained pretty well, and the authors warned the reader that it has some minor changes from the traditional implementation which was thought-provoking, and I think it will act as a subtle suggestion to help readers explore design patterns a bit more. The requirement of Flash Media Server and its AS1-style code to create the example was a bit of a turn-off for me, though.

I found ActionScript 3.0 Design Patterns to be a book that I could read from start to finish. Often I will skip sections in books that cover material I already know, but design patterns are generally pretty flexible, and it was nice to see the authors’ perspectives on them. I also had motivation to continue on because there were several patterns I haven’t yet used in my projects, and I love to learn new things. Some examples were very good and kept me interested; others felt completely out of place. In general, all of them helped me to understand how the patterns should be implemented.

If you want to learn design patterns, I think AS3DP is a good place to start if you’re most familiar with ActionScript over other languages. You may want to pick up a more general book about developing with design patterns later, though. The authors didn’t include all of the classic design patterns introduced in the original source, Design Patterns: Elements of Reusable Object-Oriented Software, and it’s probably a good idea to go beyond what’s presented in AS3DP. I’ve also heard good things about the book Head First Design Patterns, but I haven’t read it myself.

Open Source Flex Components: AdvancedList and CheckBoxList

by Josh Tynjala

The ZoomFrame component for Flex that I released last month got some good buzz. Today, I’m ready to release two more Flex components. Both are simple, but useful. The AdvancedList component adds a bit of functionality to the basic List. The CheckBoxList component adds a special item renderer with a CheckBox, and its selection changes hook into the standard List selection system. Have a look at the demo of AdvancedList and the demo for CheckBoxList to get an idea of how each works.

Screenshot of AdvancedList Component Example

The AdvancedList adds two nice things. First, you have the ability to disable specific items in the List through the data provider. They won’t be selectable through user interaction. This is achieved through the enabledField and enabledFunction properties. They work very much like the standard labelField and labelFunction properties. Additionally, AdvancedList gives you more control over drag-and-drop operations. By default, items that are dragged from a List get the drag format type “items” and any List will accept these items if dropEnabled is set to true. However, what if you have several List on screen, all are able to accept dropped items, but you want to restrict drag-and-drop between certain specific Lists? With the ability to change the dragFormat from “items” to something more specific like “shoppingCartItems”, you have more options and control.

Screenshot of CheckBoxList Component Example

CheckBoxList, as I mentioned, creates a List where selected items are shown with CheckBoxes. Multiple selection is enabled by default, and pressing the Ctrl key is not required. This component has a couple advantages. First, a collection of related CheckBoxes is now enclosed in a scrolling List. This saves on space, and we all know many apps need all the extra space they can get. Plus, the frame helps to visually associate the CheckBoxes as a set. Secondly, this component can replace a regular multi-select list. If you’ve ever seen a web form where one of these lists is used, you’ll know that they must always have instructions to tell you to press the Ctrl or Command key to select multiple items. That’s barely usable. In fact, I’d be afraid to watch my grandma if she had to enter data into that form. Instead, the CheckBoxList offers a familiar concept, standard CheckBoxes, and it puts them within another familiar concept, a scrolling List. No instructions needed.

Of course, just like the ZoomFrame component, the source code for the AdvancedList and CheckBoxList components are available under the terms of an MIT-style license. Please feel free to use them in both commercial and open source projects. There are a few other components I intend to release after some polishing, so be sure to check back soon.

Speaking at Adobe MAX 2007

by Josh Tynjala

It seems that I convinced the powers-that-be to let me go to Adobe MAX again, and this year I’ll be speaking and representing Yahoo! We’ve got an Inspire session all lined up to talk about integration. Integration of what? Flash, JavaScript, Yahoo! web services, AIR, and more.

For my part of the session, I’ll be talking about the integration of Flash visualizations with the ever-popular YUI library. I’ll be pushing the power and advantages of Flash visualizations into the hands of frontend developers who normally work with other technologies. I can’t wait to share more details about this one. We’re cooking up some cool stuff.

Session Outline

About a year ago Yahoo! has launched the very successful Yahoo Developer Network around tools, services, examples, and developer support. Yahoo! has also been working internally on Flash and Flex for a long time and released Web-Service APIs and most recently component libraries around Flash with a similar approach as YUI has done for JavaScript. In this session we are going to show examples on how we use those technologies as well as how you can create your own applications and use Yahoo! services and components. Examples shown range from AIR and Search, Flash and Ajax, over to Yahoo! Badging, WebAPIs and developer tools.

When is it?

Tuesday, October 2nd, 2007. 9:15 am – 10:15 am.

More Information

Yahoo! Presents Examples of Integration

If you’ll be at MAX, be sure to say hi if you see me. If you attend our session, I’d love to chat if you afterwards if you want to share some of cool ways you’re planning to use our components and libraries, or if you have suggestions for how we can improve our open source Flash efforts at Yahoo! Got an interesting component for Flash or Flex that you need? We might think it’s useful and cool too. Let us know at MAX!

Yahoo! launches Flash library and blog (and I helped!)

by Josh Tynjala

Today and over the last week, I’ve been a part of several big launches and redesigns at Yahoo!, and I thought I’d share a little about each with you. We’ve got exciting things happening on the Flash Platform team on the Sunnyvale campus, and hopefully, this week’s activities will only be the start.

First, I highly recommend that you check out what’s new at the Flash Developer Center on the Yahoo! Developer Network. We’ve got a brand new library up for download that adds some cool user interface components to Flash CS3. You’ll find an AutoComplete component, a Menu, a Tree, a TabBar, and my personal favorite, four different Charting components. All free and available under the terms of terms of the BSD license.

That’s not all, of course. In no particular order, here’s everything I’ve been involved with that has either launched for the first time or gone through big changes this week.

Like I said, I’m excited about all the changes made in the last week. Flash is a great web technology, and many folks at Yahoo! certainly enjoy developing with ActionScript. Don’t worry, we definitely have Flex on our radar too. Expect to see more cool libraries for Flash technologies in the future. Now, quit reading, go download the Astra Flash Library, play with the cool new components, and join the ydn-flash group to discuss it. We’d love to hear about any bugs you discover (it’s still beta, after all), and please don’t be afraid to ask us for new features (or even entirely new components!).

Runtime Enforcement of Abstract Classes in AS3

by Josh Tynjala

As you probably know, abstract classes are not a language feature of ActionScript 3. If you are unfamiliar with the concept of an abstract class, let me explain. Think of an abstract class as a super-powered interface. It defines a series of functions that must be implemented, and it cannot be instantiated directly. It goes a step beyond an interface because it also defines some functions that are already fully implemented.

To use an analogy, all electronic devices generally have the same connector to plug into the wall. However, not all electronics have the same purpose. A coffee maker and a DVD player do very different things. We could make an interface IElectronicDevice to make sure they all have a plugIntoWall() function, but then every device will need to re-implement the common wall plug functionality that doesn’t differ very often. By making a class AbstractElectronicDevice, we can implement the wall plug functionality once, and all subclasses of AbstractElectronicDevice will be able to use it without re-implementing the same code.

The problem, of course, is that the coffee maker and DVD player have different controls for turning power on and off. The coffee maker might have a switch, while the DVD player has a button. We can’t implement the togglePower() function in AbstractElectronicDevice because many electronics will have different controls, so we need some way to force all subclasses of AbstractElectronicDevice to implement this function themselves. Using the methods developed to enforce Singletons in ActionScript 3 as a guide, I’ve found a way to enforce the abstractness of a class at runtime upon instantiation.

There are two main parts to enforcing an abstract class. First, we must stop a developer from instantiating the abstract class directly. To do this, the constructor needs a little special sauce. Since anyone can create an instance of a public class by simply using the new keyword, we need the constructor of our abstract class to require a parameter that only subclasses will be able to pass. Second, we must ensure that a developer implements functions that the abstract class has defined, but not implemented.

Stopping Direct Instantiation of an Abstract Class

The magic bean to stop a developer from instantiating a class directly is one keyword: this. You don’t have access to an instance of a class until after you call a constructor, so only an instance of a subclass will be able to pass a reference to itself to the super class. Let’s look at some code to help make things clearer.

The instance of MyAbstractType expects to receive a reference to itself as the first parameter in the constructor. If it does not, an error will be thrown.

package com.joshtynjala.abstract
{
	import flash.errors.IllegalOperationError;

	public class MyAbstractType
	{
		public function MyAbstractType(self:MyAbstractType)
		{
			if(self != this)
			{
				//only a subclass can pass a valid reference to self
				throw new IllegalOperationError("Abstract class did not receive reference to self. MyAbstractType cannot be instantiated directly.");
			}
		}
	}
}

Only MyConcreteType and other subclasses of MyAbstractType will be able to pass a reference to the instance to their super() constructors. Notice that users of MyConcreteType don’t need to know that it extends an abstract class. The signature of the MyConcreteType’s constructor can be completely different than MyAbstractType.

package com.joshtynjala.abstract
{
	public class MyConcreteType extends MyAbstractType
	{
		public function MyConcreteType()
		{
			//pass "this" to clear the abstract check
			super(this);
		}
	}
}

Forcing Implementation of Functions in Subclasses

Next, like with an interface, we need to force subclasses of our abstract class to implement specific functions. Ideally, we want this enforcement to happen immediately when the object is created (to make bugs visible as early as possible). After we check that the user isn’t trying to instantiate the abstract class directly, we should check to be sure the unimplemented methods are overridden. We can do by checking the results from the flash.utils.describeType() function against a list of unimplemented methods in the abstract class. Again, a little code should give us a clearer picture.

In MyAbstractType, after we check for a reference to the self parameter, we build a list of unimplemented functions in an Array. Next, we use describeType() to get a list of the methods declared in the instance. If a subclass of MyAbstractType overrides a method, the declaredBy attribute in the method XML will specify the name of the subclass rather than MyAbstractType.

package com.joshtynjala.abstract
{
	import flash.errors.IllegalOperationError;
	import flash.utils.describeType;
	import flash.utils.getQualifiedClassName;

	public class MyAbstractType
	{
		public function MyAbstractType(self:MyAbstractType)
		{
			if(self != this)
			{
				//only a subclass can pass a valid reference to self
				throw new IllegalOperationError("Abstract class did not receive reference to self. MyAbstractType cannot be instantiated directly.");
			}

			//these functions MUST be implemented in subclasses
			var unimplemented:Array = [mustBeOverridden];

			//get the fully-qualified name the abstract class
			var abstractTypeName:String = getQualifiedClassName(MyAbstractType);

			//get a list of all the methods declared by the abstract class
			//if a subclass overrides a function, declaredBy will contain the subclass name
			var selfDescription:XML = describeType(this);
			var methods:XMLList = selfDescription.method.(@declaredBy == abstractTypeName && unimplemented.indexOf(this[@name]) >= 0);

			if(methods.length() > 0)
			{
				//we'll only get here if the function is still unimplemented
				var concreteTypeName:String = getQualifiedClassName(this);
				throw new IllegalOperationError("Function " + methods[0].@name + " from abstract class " + abstractTypeName + " has not been implemented by subclass " + concreteTypeName);
			}
		}

		//implemented
		public function alreadyImplemented():void
		{
			trace("Don't forget to list me in the Array of valid functions.");
		}

		//unimplemented
		public function mustBeOverridden(param:String):void {};
	}
}

Now, in MyConcreteType, we can implement the mustBeOverridden() function. If we do not, an error will be thrown. To be certain, try commenting out the implementation of mustBeOverridden() in MyConcreteClass. If you instantiate it, you will receive a runtime error.

package com.joshtynjala.abstract
{
	public class MyConcreteType extends MyAbstractType
	{
		public function MyConcreteType()
		{
			//pass "this" to clear the abstract check
			super(this);
		}

		//implemented
		override public function mustBeOverridden(param:String):void
		{
			trace("param:", param);
		}
	}
}

Conclusions

As you probably noticed, the first part of implementing an abstract class is very simple. Making the abstract class receive a reference to itself enforces subclassing, and it can be done in only a few lines of code. The second part, making an abstract class work like an interface, requires a lot more code, and it may be more prone to errors. You, as a developer, must remember to add all the unimplemented methods to the Array in the constructor. Additionally, if the class gets large, I can imagine that calling describeType() often enough could lead to performance problems. In most cases, as long as you keep your classes clean, it should work well. I highly recommend the subclass enforcement, but I wouldn’t be heartbroken if you feel that checking for unimplemented methods is overkill.

Source code for this tutorial is available for download. It includes all the code above plus an extra implementation (for comparison) of the “electronic device” example I described at the beginning. It’s all under the terms of the MIT license.

Frustration with accessibility in Flash and Flex

by Josh Tynjala

After adding accessibility support to some Flash components I’ve been developing recently, I wanted to give them a test drive. To my surprise, I discovered that Flex and Flash components that Adobe claims are accessible aren’t very usable in a screen reader environment. I have always pointed out to people who claim that Flash isn’t accessible that Flash Player supports screen readers, but it must be specifically enabled by the developer. Until I see better results (even from the official Flex components!), I will no longer make that argument.

I started my adventure by installing a trial of JAWS, the most popular screen reading software on the market. The trial will run for 40 minutes at a time, and if you restart your computer, the counter will reset and you can use it again. It’s a pretty decent solution for software developers who want to test their work. It gets kind of annoying to wait while my messenger and email programs start every time I restart my computer, but it’s better than paying $900-$1100 for a full version of JAWS.

Testing JAWS with Flex

My first test of JAWS is with a simple Flex project with a single TabBar component. I turn on accessibility for the TabBar with the creationComplete event, and I give the it three tabs, “Web”, “Images”, and “Local” (like you might see on a search engine). I start up my browser, but the screen reader doesn’t have much to read.

Flash Movie Start. Flash Movie End.

It seems Flash Player doesn’t fully support accessibility within Firefox. Unfortunate. I wonder if it’s a browser problem or Adobe’s problem? Annoyed, but still open-minded, I ran the SWF in IE instead. JAWS gave me much more information, but I found some bugs with the component almost immediately. Here’s what JAWS read to me.

Flash Movie Start. Web Tab. Active Tab. Images Tab. Tab. Local Tab. Tab. Flash Movie End.

It says “Tab” twice for every Tab that it encounters. Navigating around tabs in native Windows applications doesn’t give me that problem. It’s not a big deal, but I definitely got a good first taste of unpolished accessibility features. Next, I start testing keyboard navigation. I press the Down arrow key.

Images Tab. Tab.

So far, so good. The “Images” tab has been highlighted, but not yet selected. I press the spacebar to select the tab.

Space.

Hmmm… did it work? I can see that it did because the Tab is now selected, but a blind user only knows that they pressed the spacebar. Maybe screen readers just automatically assume that the default action is successful. Sounds potentially confusing. I’d hate to be a blind developer with buggy code. I press the Up arrow key to go back to the “Web” tab.

Web Tab. Active Tab. Images Tab. Tab. Local Tab. Tab.

Uh oh. That seems wrong. First, the behavior has changed. Instead of simply telling me that the “Web” tab has been highlighted, JAWS has decided to read off the full contents of the TabBar again. Moreover, the TabBar has the “Images” tab selected now, but the screen reader is still reporting that the “Web” tab is active. That single bug is bad enough to make TabBar completely unusable to a blind user.

I tried testing a couple more components from Flash and Flex. The most potentially embarrassing for Adobe is that I can’t seem to figure out how to press Flash CS3′s Button component. I can use the Tab key or the Down arrow to navigate between them, and JAWS will read the labels, but the spacebar won’t press them. Also, in a Windows operating system dialog, the screen reader will say “To activate, press spacebar” when a button is highlighted. Why isn’t this more consistent?

My conclusion from several tests is that the official Flash and Flex components are hardly worthy of the title “accessible”. That’s only half the battle, unfortunately. Actually trying to build a custom component that supports screen readers is even more frustrating.

Implementing Accessibility

It didn’t take me long to discover that Adobe implements accessibility for their components differently than the officially suggested methods. Outlined on the Flash CS3 Accessibility pages (by comparison, the Flex accessibility information on Adobe’s site is completely out of date), accessibility should be handled through the Accessibility panel or with the “accessibilityProperties” property on DisplayObject. It is of type flash.accessibility.AccessibilityProperties. It seems pretty straightforward to use, but I haven’t played with it much yet. Why? Well, it’s because Adobe doesn’t use it for their components, and I want to handle accessibility the way they did it.

If you look in flash.accessibility.* package in the Flex 2 LiveDocs, you’ll see two classes, AccessibilityProperties and the main Accessibility class. You might also notice that the mx.accessibility.* package doesn’t get listed at all. This package contains the accessibility implementations for each of the Flex components, like Button, List, ComboBox, TabBar and everything else. Not a big deal, I guess, but now I have to dig into my file system and open these classes directly to learn more about them. When I started exploring this area, I discovered some very strange things.

The base accessibility class in Flex is named mx.accessibility.AccImpl. The equivalent in Flash CS3 is fl.accessibility.AccImpl. All the concrete implementations, like ButtonAccImpl for the Button component or TabBarAccImpl for TabBar, extend this class. Here’s where things get intersting: AccImpl itself extends another class named flash.accessibility.AccessibilityImplementation. “But wait,” the observant reader says, “I don’t remember seeing that class in the flash.accessibility.* package when I checked the LiveDocs.” Me either. This has led me to a lot of frustration because the functions from this class that get overridden in classes like ButtonAccImpl aren’t explained very well.

Adobe has chosen to hide what appears to be the most important class for implementing accessibility in components from the rest of world. Both the Flash CS3 components and the Flex components use this class, so it must be useful and important. Why isn’t it documented? Is there some reason why I wouldn’t want to use this class in my own component framework?

Much to my dismay, I also discovered the following comment from the source code for the Flash CS3 accessibility classes:

Nivesh says: I don’t think we should document the constructors for the accessibility classes.

The reason he says that is because the user of the class isn’t supposed to instantiate the accessibility implementations directly with the constructor. Instead, there’s a static enableAccessibility() function that needs to be called. Unfortunately, from that comment alone, I can’t help but wonder what other documentation is missing from these classes. In my opinion, the documentation for accessibility is the worst I’ve seen from Adobe, and after a week of messing with their stuff, I sent in a very long feature request for “extensive documentation”, and I gave up on one of my projects until I can spend a lot more time studying screen readers and Flash Player. Nivesh, please don’t remove anything that might be useful. Developers using ActionScript 3 will look closely at Adobe’s work to help pick up best practices and ideas, and you can bet that we want to know problems you run into and learn about things that we aren’t supposed to do. Document, document, document.

How Adobe can improve accessibility in Flash and Flex

  1. Update the online documentation for Flex accessibility or remove it. Information for Flex 1.5 doesn’t help me much when Flex 3 is just around the corner.

  2. Give me a walkthrough or two about how to make a real component accessible. Go through it step by step as if I’m an absolute novice. The fact is, most developers using any language or environment don’t know anything about accessibility. Include information on common problems we might encounter when trying to build accessible components. I’d love to see information about how to develop an accessible component that has subcomponents that are already accessible. What if I want to use their default behavior? What if I want to ignore the default behavior completely?

  3. Adobe, if you’re going to use flash.accessibility.AccessibilityImplementation, you can bet that everyone else will want to use it too. Either stop hiding it, or stop using it because it’s not fair to us. Put this class in the documentation and describe it in detail. Walk through every single function available on this class, and explain exactly what these functions do, along with how and when they will be used by the screen reader.

  4. Make accessibility subjects more visible in the documentation. At the very least, try to work the subject in more often. Developers don’t think of accessibility because we don’t encounter it often enough. For instance, for every component in Flex, there’s a page in the docs that offers a short introduction, it might have a bit of source code, and it describes how the component works. Is there a description of how each component appears to screen readers on those pages? There should be.

If you made it this far, thanks for listening to me vent. Accessibility is very important, and the need for it will only become more important in time as laws get stronger. Based on my short experience trying to make Flash and Flex components accessible, I’m a little embarrassed by the obviously untested components from Flex and the difficulties of setting it all up myself. I’m no accessibility expert, though, so please add comments below if you know of some good tricks that I may have missed, or if you have any insights about the undocumented AccessibilityImplementation class. I’d love to find links to good resources for Flash accessibility too. If you’re an Adobe employee, please make sure my comments go to the appropriate audience within the company. I’d love to see improvements based on my troubles. Thanks!

Pages: Prev 1 2 3 4 5 6 7 8 9 10 ...19 20 21 Next