July 28, 2007

composition vs inheritance for Sprite and MovieClip

a reader recently wrote me with some questions he posted to a newsgroup about inheriting from Sprite in ActionScript 3.0 vs inheriting from MovieClip in ActionScript 2.0. it's an important topic, so i figured i'd post the exchange here, starting with the reader's newsgroup posting:

I have been until now a fervent disciple of compositing a graphic instance into a class in every case, rather than making my class extend MovieClip. Admittedly I was a piker at AS2 and only now that I am cranking on AS3 do I consider myself worthy to call myself a beginner OOP programmer. But I bought into all the reasons, and if I were still making AS2 apps, I might remain in that camp.

But lately my devotion has been shaken and now I am seriously considering extending (and then subclassing from) MovieClip or Sprite when making any class which has a visual component. Whereas before I would always compose in a MC instance, almost never make my class inherit from anything but my own superclass, and implement interfaces for polymorphism, now I think I will extend, although still implement interfaces for the usual other reasons. I also still plan to be a composition devotee in all other ways-- I like composition more than inheritance. Also I would not extend MC for classes which have no graphical component, such as game logic components. (I am making games and other interactive entertainment apps, for in-browser distribution.)

Here are a few reasons why my mind is changing; please feel free to refute or support any of these:

--Changes between AS2 and AS3 make the downside of subclassing MC/Sprite smaller than before. I'll let far more informed people come up with good examples, but one seems to be the explicit nature of adding an object to the display list-- the overhead hit of being an MC is small (nonexistent?) if it is not on the list.

"Essential ActionScript 2" advocates composition-- see the large MVC example in which a view class, although nearly entirely visual in function, did not extend MC but rather composited MC. However, in Moock's equally impressive AS3 book, all his examples now seem to use extension. This gives me a new perspective.

--All the Adobe best practices and examples use extension, as do nearly all code samples I see in other helpful forums. I am not one to blindly run with the crowd but I think I'd get better feedback on my code from my peers if I follow suit.

--All the AS3 Flash components seem to use extension, and indeed, AS3 itself is heavily inheritance-based rather than composition-based, for understandable reasons.

I am probably missing a lot and mis-stating much of what is there but hopefully you get the idea.

So once again I ask my better peers: what are now the arguments for and against extending MC or Sprite for one's visually represented classes in AS3? Any observations would be much appreciated.

Also, in Essential ActionScript 2.0 there is an extensive example of the MVC pattern involving, what else, a clock. In his code his Clock view does *not* extend MovieClip (Sprite not having been available in AS2), which is in keeping with his general admonition to compose a graphic element into a class rather than extend one. His view's constructor takes an MC as an argument, and the view attaches its MC instance (which contains all the clock visuals) to the passed MC. The view object is not itself attached, because it is not an MC. The view class contains an MC which ends up getting attached. To change the XY of the view would be to ask the view to change its MC instance's XY. Pure composition.

In Essential ActionScript 3.0 there's an extensive "Virtual Zoo" example which among other things uses an MVC-ish structure, in which the view and controller are the same class. If anything, this would make composing in the view's root graphic element even more sensible than his AS2 example. The View does not really fit the definition "is-a Sprite"; it also is a view manager and controller. But, contrary to his AS2 stance and in keeping with all the other examples in his AS3 book, Moock's view class *extends* Sprite, and is added as a child by the main class. Though the view does happen to contain objects which are also made from Sprite-extending classes (pictures of the zoo animal and the like), the view class does not contain its root sprite the way the AS2 example contained its root MC. The view *is* a Sprite. To change the XY of the view would be to simply set its inherited XY properties from the outside, as any Sprite would be positioned. So though Moock still is a devotee of composition in every other way, on this one point he seems to have decided to use inheritance and take a path different from his AS2 book.

And I have seen most other AS3 code examples follow suit. The Lott AS3 book does, and all the Adobe examples do. So forgive me for having my faith shaken a wee bit.

Though I remain convinced of the rule to favour composition, in this particular set of cases I am considering routinely using inheritance, even though I easily *could* use composition. It just seems to be messier, denser, and longer to use composition *in this set of cases*. So is my reasoning good, faulty, or does it simply betray deep cluelessness about OOP?


hi matthew,
as with all design choices in programming, the question of composition vs inheritance comes down to a cost/benefit analysis. in ActionScript 2.0, the only way you could create a logical "type" of display asset was to subclass MovieClip. the cost of implementing MovieClip subclasses was quite high because:

-you had to link a class to a particular .fla
-you had to use arcane syntaxt to create objects (attachMovie())
-the initialization process was messy (no constructor arguments)

i preferred composition over inheritance for MovieClip objects in ActionScript 2.0 partly because the cost of implementing inheritance was so high. the composition alternative sheltered users of my code from those costs.

in ActionScript 3.0, the system for creating a logical "type" of display asset is much cleaner. you simply extend Sprite, and use the subclass like any other class in your program. there's no need to link your class to a movie clip symbol in a .fla (though that's still possible), and you can use normal "new" syntax to create instances, complete with constructor arguments.

so in ActionScript 3.0, the composition approach actually has a higher cost than the inheritance approach because composition requires more code. hence, the cost/benefit question in ActionScript 3.0 is: are the benefits of composition worth the extra code? recall that the benefits of composition are: 1) a more logical class hierarchy, and 2) the ability to extend a logically appropriate class while still using the composed class's functionality.

in simple programs, such as the VirtualZoo, I think composition can be overkill, particularly in the case of the Sprite class. in fact, I would argue that the VirtualPetView can legitimately be thought of as a specialized type of Sprite. conceptually, what is a Sprite? it's a displayable graphic that supports interactivity. what is a VirtualPetView? it's a specific graphic (a pet) that supports a specific type of interactivity (feeding). in other words, VirtualPetView is a specialized type of Sprite, much as a Automobile is a specialized type of Vehicle.

now let's turn to the question of separating the controller from the view in the virtual zoo program. as you point out, VirtualPetView contains both the controller and the view. does that make sense? is the VirtualPetView class becoming bloated and difficult to read? probably a little. if the pet had more interactivity (grooming the pet, teaching it tricks, etc), I think it would be wise to separate input from display. in fact, i even wanted to write a chapter showing the benefits of full mvc by breaking the VirtualPetView into two classes. but at 900 pages and 2 years of writing, a full discussion of mvc was one of the things that got cut from the book.

nevertheless, it's perfectly natural to start with a class that combines the controller and the view, and then later refactor the class to separate the controller from the view. again, for a small program, combining the controller and the view into a single class is less work. as i often say, if the program runs and does what you want it's "right". later, if the program scope increases, you can pay the cost of writing a little more code in exchange for the benefits of greater flexibility and readability.

there are no right answers with this stuff. you have to decide what makes sense for your program. the fact that you are asking these questions means that you are programming the "right" way.

thanks for the interesting question!


Posted by moock at 08:53 PM

July 27, 2007

Chapter 31, Pages 1-3, Essential ActionScript 3.0

Here are the first 3 pages of Chapter 31 of Essential ActionScript 3.0. This is the final chapter preview.

31. Distributing a Class Library

This chapter discusses three specific techniques for sharing a group of classes (a class library) among multiple projects and multiple developers. By far the easiest way to share classes is to simply distribute the source code. We’ll cover this easiest case first, before we learn how to share classes without distributing source code, as you might want to do when selling a professional class library.
The term “class library” is programmer jargon for an arbitrary group of classes distributed to a team or to the world at large. Don’t confuse it with a .fla file’s Library or the Flash Library panel. Those terms are unique to the Flash authoring environment and not part of the current discussion.

In ActionScript, a class library can be distributed to other developers simply as a bunch of source .as files, in a .swf file, or in a .swc file. We’ll cover all three approaches in this chapter. Note, however, that ActionScript offers a wide range of options for distributing class libraries; this chapter covers three specific canonical situations, but is not exhaustive. For more information on distributing class libraries, see the following Adobe documentation:

* Programming ActionScript 3.0 > Flash Player APIs > Client System Environment > Using the ApplicationDomain class (http://livedocs.macromedia.com/flex/201/html/18_Client_System_Environment_175_4.html)
* Building and Deploying Flex 2 Applications > Building Flex Applications®Using Runtime Shared Libraries (http://livedocs.macromedia.com/flex/201/html/rsl_124_1.html)

The example files discussed in this chapter are available at http://www.moock.org/eas3/examples.

Sharing Class Source Files

Let’s start with the simplest way to distribute a class library: sharing class source files.

Suppose you work in a small web shop called Beaver Code, whose web site is http://www.beavercode.com. You’ve made a class—com.beavercode.effects.TextAnimation—that creates various text effects. You want to use the TextAnimation class on two sites you’re working on, Barky’s Pet Supplies and Mega Bridal Depot. Rather than place a copy of the class file (that is, TextAnimation.as) in each project folder, you store the class file centrally and merely refer to it from each project. For example, on Windows, you store TextAnimation.as in the following location:


To make the TextAnimation class accessible to both projects, you add the directory c:\data\actionscript to each project’s classpath (the classpath is discussed in Chapter 7).

By the same logic, if there were several members on your team, you might think it would be handy to store your classes on a central server so everyone would be able to use them by adding the server folder to their project’s classpath. For example, you might want to store all shared classes on a server called codecentral, as follows:


But working directly off the server is highly perilous and not recommended.
If you store your classes on a central server and allow developers to modify them directly, the developers are liable to overwrite one another’s changes. Furthermore, if the clock of the server and the clock of a programmer’s personal computer are not in perfect sync, then the latest version of the class might not be included in the program at compile time. To avoid these problems, you should always use version control software to manage your class files when working on a team. Two popular (and free!) options are CVS (see http://www.cvshome.org) and Subversion (http://subversion.tigris.org).

On large projects, you might also want to automate the .swf export process using a build tool such as Apache Ant (http://ant.apache.org).
For information on using Ant with Flex Builder 2, see Using Flex Builder 2 > Programming Flex Applications > Building Projects > Advanced build options > Customizing builds with Apache Ant (http://livedocs.macromedia.com/flex/201/html/build_044_12.html).

To automate .swf export in the Flash authoring tool, you’d have to execute a command-line JSFL script to tell Flash to create the .swf for each .fla file in your project. Complete coverage of command-line compilation with Flash is outside the scope of this book, but here’s a quick sample that gives the general flavor of it on Windows:

// Code in exportPetSupplies.jsfl:
// ===============================
// Open the .fla file.
var doc = fl.openDocument("file:///c|/data/projects/pet/petsupplies.fla");
// Export the .swf file.
doc.exportSWF("file:///c|/data/projects/pet/petsupplies.swf", true);
// Quit the Flash authoring tool (optional).

// Command issued on command line from /pet/ directory:
// ====================================================
"[Flash install_folder]\flash.exe" exportPetSupplies.jsfl

For the preceding example command to work, Flash must not be running. After the command is issued, the compiled petsupplies.swf movie appears in the directory c:\data\projects\pet.

Posted by moock at 10:39 PM

July 26, 2007

Chapter 30, Pages , Essential ActionScript 3.0

Here are the first 3 pages of Chapter 30 of Essential ActionScript 3.0

30. A Minimal MXML Application

In Chapter 20, we learned that the Flex framework includes a sophisticated collection of customizable components for creating user interfaces. The Flex framework’s user interface components are typically used with MXML-based applications, but can also be used in applications written primarily in ActionScript. For the benefit of readers who do not wish to use MXML, this chapter describes the bare minimum steps required to use the Flex framework’s UI components in a Flex Builder 2 project, with as little MXML as possible.

For the record, this chapter has nothing against MXML. In general, MXML is an excellent tool for creating standardized interfaces deployed to the Flash platform. This chapter simply caters to situations where either an application’s layout is entirely programmatically generated or where the developer does not have the time or interest to learn MXML.

For complete information on MXML and the Flex framework, see Adobe’s documentation and O’Reilly’s Programming Flex 2 (Kazoun and Lott, 2007).
Users of the Flash authoring tool should note that Flash CS3 includes its own set of user interface components in the package fl. The Flash CS3 components can also be used (both technically and legally) in ActionScript programs compiled with Flex Builder 2 or mxmlc.

The General Approach

Here are the minimal steps for creating an application that uses the Flex framework’s UI components via ActionScript:

1. In Flex Builder 2, create a Flex project.
2. In the new project, define a class with a static method that will act as the application’s point of entry.
3. In the project’s main MXML file, add an MXML event property that listens for the top-level Application instance’s FlexEvent.APPLICATION_COMPLETE event, and invokes the static method from step 2 in response.
4. In the static method from step 2, create the desired UI components, and add them to the Application instance.

The following sections describe the preceding steps in detail.

Create the Flex Project

To create the project for the application, we follow these steps:
1. In Flex Builder 2, choose File®New®Flex Project.
2. On the New Flex Project dialog, for “How will your Flex application access data?,” select Basic, then click Next.
3. For Project name, enter the desired project name, then click Next.
4. For Main source folder, enter src.
5. For Main application file, enter the desired filename, with the extension .mxml. For example, MinimalMXML.mxml.
6. Click Finish.

In response to the preceding steps, Flex Builder 2 creates a new project whose Library path automatically includes the file framework.swc, which contains the UI components.

Once the project has been created, we create the application’s point of entry, as described in the next section.

Create the Application Point of Entry

Our application’s point of entry is a static method defined by a custom class. In our example, we’ll name the static method main() and the custom class EntryClass. The main() method creates the UI component instances and adds them to the top-level Application instance’s display hierarchy. The top-level Application instance is an automatically created object that acts as the basis of all MXML applications, and provides access to the display list. Throughout our program, the top-level Application instance can be accessed via the mx.core.Application class’s static variable, application.

Example 30-1 shows the code for EntryClass.

Example 30-1. The ActionScript class for a minimal MXML application

package {
  import mx.controls.*;
  import mx.core.*;
  public class EntryClass {
    // Application point of entry
    public static function main ():void {
      // Create Flex framework UI components
      // For example:
      var button:Button = new Button();
      // Add UI components to the screen
      // For example:
      var mxmlApp:Application = Application(Application.application);

Once the EntryClass.main() method has been created, we can invoke it in response to the top-level Application instance’s FlexEvent.APPLICATION_COMPLETE event, as described in the next section.

Trigger the Application Point of Entry

Earlier under “Create the Flex Project,” we specified MinimalMXML.mxml as our example project’s main application file. As a result, Flex Builder 2 automatically inserts the following code into that file:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

We need to make only one minor change to the preceding MXML code: we must add an event property that invokes EntryClass.main() when the top-level Application instance receives FlexEvent.APPLICATION_COMPLETE event notification. The following bolded code shows the approach:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="absolute" applicationComplete="EntryClass.main()">

In response to the preceding code, when the application has finished initialization, it will automatically invoke EntryClass.main(), which, in turn, creates the desired UI component instances. (Look mom, no MXML!)
Let’s apply the general approach covered in the preceding sections to a real example.

Posted by moock at 08:21 PM

July 13, 2007

two places to learn about air

if you want to learn about Adobe AIR (the flash/html/javascript desktop runtime), here are two good (and free) places to start:

>> the AIR bus tour (live event, july 10-sept 29)
>> apollo alpha preview with mike chambers (online video)

Posted by moock at 04:49 PM

July 12, 2007

ecmascript gets a home on the web

the ecmascript committee has posted a collection of official information about ecmascript at:


the site includes links to specifications and a reference implementation of ecmascript edition 4 written in Standard ML.

Posted by moock at 04:59 PM