You are currently browsing the Eric Feminella blog archives for September, 2007


MAX 2007 in Chicago

I arrived in Chicago earlier this afternoon as I will be attending MAX North America from Sunday – Wednesday.

This is my first time visiting the “Windy City” and it is a really nice place; very clean and very quite for such a large city, or maybe that’s just because I am used to NYC?

I am staying at the Hilton Towers and the food and drink at Kitty O’Sheas is worth the trip alone. The hotel also has a very interesting historical background as well.

If you should happen to be attending MAX as well feel free to look me up.

I am planning on writing a post soon after I return regarding what I feel were some of the more significant highlights of MAX 2007.

Enforcing an all static API in ActionScript 3

It is quite common when designing an API or system in Adobe Flex that you will identify certain areas which call for specific classes to contain an all static API.

Typically, all-static classes are utilized as helper, utility and factory classes which provide static methods for performing common utility methods.

A commonly overlooked aspect of such designs is the assumption that an all-static class will not be misused by clients, specifically via instance instantiation, as it is assumed by the designer that an all static class would never be instantiated as there are no instance members available, only static class members. This is a fair assumption. However it is not possible to guarantee this will never occur as ActionScript 3 does not support private constructors (yes, I am back on this subject yet again). Although this is an unfortunate limitation of the language it should not deter you from enforcing such restrictions.

To help facilitate these restrictions in my own designs I have created a very simple, yet effective Abstract class called AbstractStaticBase, which helper and utility classes can extend in order to ensure they are never instantiated.

Classes which contain an all static API can extend AbstractStaticBase in order to ensure they can never be instantiated. This is the only requirement.

AbstractStaticBase is lightweight as it only contains a constructor. The constructor does nothing more than create an Error object and parse the call stack to determine the fully qualified name of the concrete class which has been instantiated, the message property is then set on the Error object and thrown.

Implementation on the clients part is very straightforward as all that is required is to extend AbstractStaticBase.

Consider the following example. CalcUtil is an all static class, to ensure an instance of CalcUtil is never instantiated simply extend AbstractStaticBase as follows:

package com.domain.utils
{
    import com.ericfeminella.AbstractStaticBase;

    public class CalcUtil extends AbstractStaticBase
    {
         public static function calculate() : Number
             {
             // implementation not pertinent to subject
         }
    }
}

// an attempt to instantiate CalcUtil …
var util:CalcUtil = new CalcUtil ();
 
// results in the following exception:
// Illegal instantiation attempted
// on class of static type: com.domain.utils::CalcUtil
 

So if you want to enforce that static classes are never instantiated, simply extend AbstractStaticBase.

Multiton Pattern in ActionScript 3

If you are familiar with the standard GoF Patterns than you more than likely are aware of the Singleton Pattern and the solutions which it provides.

For those of you who are not familiar with the Singleton Pattern it is a Creational Pattern which, when implemented as prescribed ensures only one instance of a class is ever instantiated. This is facilitated via a single global access point from which a singleton instance is to be created and or retrieved.

You may be wondering just what the Singleton Pattern has to do with the Multiton Pattern? And how does the Singleton pattern relate to the Multiton pattern? What are the differences and what are the similarities?

To answer your question the Multiton pattern is a Creational pattern which builds on the concept of the Singleton pattern by adding a mapping of key / value [object] pairs.

Unlike the Singleton Pattern, whereas there is only ever a single instance of an object created, the Multiton pattern ensures that only a single instance of an object is created per key. Therefore there are multiple instances which are managed via the Multiton object. The Multiton pattern provides centralized access of Multiton objects and advocates keyed storage of objects within a system.

Below is a simple example which demonstrates an implementation of the Multiton Pattern in ActionScript 3.0:

package
{
  import com.ericfeminella.utils.HashMap;
  import com.ericfeminella.utils.IMap;
   
  public final class Multiton
  {
      private static var instances:IMap = new HashMap();
       
      public function Multiton(access:Private)
      {
          if (access == null)
          {
              throw new Error( "Abstract Exception" );
          }
      }

      public static function getInstance(key:*):Multiton
      {
          var instance:Multiton=instances.getValue(key);

          if ( instance == null )
          {
              instance = new Multiton( new Private() );
              instances.put( key, instance );
          }
          return instance;
      }
       
       public function get id() : *
       {
           return instances.getKey( this );
       }
    }
}

class Private {}

Here is a breakdown of the above example.

First a new class is created as well as an additional inner class outside of the package which is used to ensure the constructor can only be called from within the class body, in this case the Multiton class.

package
{
  public final class Multiton
  {
      public function Multiton(access:Private)
      {
          // verify that access is not null
          // if it is, then an illegal request
          // to instantiate the constructor
          // is being attempted
          if (access == null)
          {
              throw new Error( "Abstract Exception" );
          }
      }
   }
}

/**
 * inner class restricting constructor access to private
 */

class Private {}

Next a private or protected static var of type HashMap (optionally, a generic Object or Dictionary can be substituted) is defined. The static HashMap instance contains the mappings of keys to objects in the Multiton class. Each key only ever contains a single Multiton object instance, and each Multiton instance can only be accessed by it’s associated key.

package
{
  import com.ericfeminella.utils.HashMap;
  import com.ericfeminella.utils.IMap;
   
  public final class Multiton
  {
      // contains key / Multiton instance mappings
      private static var instances:IMap = new HashMap();
       
      public function Multiton(access:Private)
      {
          if (access == null)
          {
              throw new Error( "Abstract Exception" );
          }
      }
   }
}

/**
 * inner class restricting constructor access to private
 */

class Private {}

Lastly, Multiton implementations require a public static method; getInstance(); which is very similar to the static getInstance() as it applies to the Singleton pattern, but with a slightly different signature. The getInstance(); method in a Multiton requires a single parameter which specifies the key from which a new instance is to be assigned and / or retrieved.

Certain Multiton implementations use an object as the key, however it is arguably more intuitive to use a primitive type such as a String to define keys. Regardless, I prefer not to enforce type restraints as the implementation will typically depend on the context in which it is being applied.

package
{
  import com.ericfeminella.utils.HashMap;
  import com.ericfeminella.utils.IMap;
   
  public final class Multiton
  {
      private static var instances:IMap = new HashMap();
       
      public function Multiton(access:Private)
      {
          if (access == null)
          {
              throw new Error( "Abstract Exception" );
          }
      }

      // retrieve the appropriate Multiton instance
      // if the instance does not currently exist
      // one will be instantiated and mapped to
      // the specified key. All subsequent client
      // requests will return the correct instance
      public static function getInstance(key:*):Multiton
      {
          var instance:Multiton=instances.getValue(key);

          if ( instance == null )
          {
              instance = new Multiton( new Private() );
              instances.put( key, instance );
          }
          return instance;
      }
   }
}

class Private {}

To implement a Multiton instance all that is needed is to invoke the static getInstance(); on the Multiton class object just as one would invoke getInstance() on a singleton class object. However in the Multiton it is assumed that there will be many instances, albeit controlled instances, therefore a key must be specified.

Below is a simple example which demonstrates how to retrieve a specific instance of a Multiton object:

var multiton1:Multiton = Multiton.getInstance( "a" );
trace( multiton1.id ); // a

var multiton2:Multiton = Multiton.getInstance( "a" );
trace( multiton2.id ); // a

var multiton3:Multiton = Multiton.getInstance( "o" );
trace( multiton3.id ); // o

There is not to much documentation on the Multiton Pattern outside of the Ruby community and a Java implementation available on wikipedia, however the Multiton Pattern proves very useful when multiple, controlled object instances are needed.

AS3 QueryString API Update

I have upgraded the QueryString API from an all static utility class to a much more robust API which now supports parsing, inspecting and modifying query strings.

The new QueryString API retrieves a query string for a Flex application via ExternalInterface. Therefore a query string which has been supplied to an application can be retrieved from an html wrapper (e.g. .html, .jsp, .aspx, etc) as well as a .swf file.

Developers can also utilize the new API to perform CRUD operations on an arbitrary query string supplied to the QueryString constructor. I have also added complete support for encoding and decoding a query string as well as appending a query string to separate URLs.

Modifications of a QueryString are now fully supported and allow parameters in a QueryString object to be created, read, updated and deleted.

The QueryString constructor takes a url as an argument. This argument is optional, and, if specified instructs the QueryString object to use the specified url for all subsequent operations. If the url is not specified the QueryString object will assume the aplication query string is to be used for all operations.

Unfortunately, ActionScript 3 does not support constructor / method overloading so the url parameter is used to achieve the correct functionality based on context.

Below is a typical use-case which demonstrates how to instantiate a new QueryString object which defaults to the application’s querystring:

var querystring:IQueryString = new QueryString();
//defaults to application querystring

trace( querystring.getQueryString() );
//outputs application querystring

Optionally, you can choose to use a specific QueryString by passing it to the constructor:

var url:String = "http://localhost/app.html?name=Adobe Flex";

var querystring:IQueryString = new QueryString( url );
//defaults to querystring specified in constructor

trace( querystring.getQueryString() );
//name=Adobe Flex

Additional usage examples for all method can be found in the accompanying ASDoc.

You can view the source for the IQueryString interface and concrete QueryString implementation as well as the asdocs.

QueryString API is protected under the MIT license.

Adobe Thermo?

So what exactly is Adobe Thermo? Or at least what is this new product from Adobe which has been codenamed “Thermo”? I don’t think anyone outside of Adobe really knows for sure just yet…

Based on what I have read so far “Thermo” appears to be a cool new tool which will allow creative professionals to leverage their existing skills to build RIAs utilizing tools they are comfortable with such as the Adobe Creative Suite product line.

Regardless of the specifics, one thing is for certain – any new tool which builds on the Adobe Flash Platform can only be a good thing for RIA developers specializing in Adobe technologies.

So I guess we will just have to wait for MAX 2007 / Chicago in 2 weeks to find out more.

For more information check out Mark Anders post on Thermo.

Static constant definition utility

I recently was working on an application where I needed to verify that certain static constants were defined by a specific class. I have run into similar situations like this before so I decided to write a simple utility which I could reuse.

ConstantDefinitionUtil is an all static class which provides an API for determining if specific constants have been defined by a class.

Additionally, ConstantDefinitionUtil provides a method for retrieving all static constants which have been defined by a class.

The following example demonstrates how ConstantDefinitionUtil can be utilized to determine if the static constant “X” has been defined by ClassA:

package
{
    public class ClassA
    {
        public static const X:int = 1;
        public static const Y:int = 2;
        public static const Z:int = 3;
    }
}

import com.ericfeminella.utils.ConstantDefinitionUtil;

trace( ConstantDefinitionUtil.isDefinedBy("X",ClassA) ); //true
 

ConstantDefinitionUtil.as

ComboBox.prompt

This is one of those little things that you come across from time to time and think to yourself, “man, how did I not come across this before?”.

There has been so many times where I have added an item to a collection in order to display a message to the user. For instance, say you have a ComboBox that displays a list of employees and you want to add a message as the first item, specifying something to the extent of “Select an employee”. Typically, an item would need to be added to the dataProvider of the ComboBox at index 0. Then the issue arises where you will then need to take this item into account when it is selected so that it will be ignored.

Well, like most things in Flex there is an out of the box solution!

The solution is the prompt property which can be utilized to facilitate exactly this sort of thing. I stumbled across this property accidentally while extending ComboBox and viewing the source code. The prompt property simple adds an item to it’s data provider at -1. Since Array indexing begins at zero, this item is ignored and you do not have to take it into account when working with the data provider.

<mx:ComboBox prompt="Select an employee" />

Hope this helps someone down the road.

AS3 HashMap Update

I have updated the HashMap API to provide additional functionality which comes in handy when working with managed key / value pairs.

Additionally, I have also modified the HashMap class from an “is-a” to a “has-a” relationship as the previous version was a derivation of Dictionary, thus exposing the map and consequently causing a security breach in the API. This has been fixed as of this update as the map is now private rather than the object itself.

The original IMap interface I created was modeled loosely after operations which are typical of the Java Map interface. However I have identified additional operations which are useful when working with key / value pairs. These new operations have been implemented in the latest HashMap class and comprise all of the new methods.

Below is a list of the additional methods which have been implemented in the HashMap update:

  1. getValues: Retrieves all of the values assigned to each key in the specified map
  2. reset: Resets all key assignments in the HashMap instance to null
  3. resetAllExcept: Resets all key / values defined in the HashMap to null with the exception of the
    specified key
  4. clearAllExcept: Clears all key / values defined in the HashMap to null with the exception of the specified key

You can view the latest HashMap API source for the IMap interface and HashMap implementation. Each method is accompanied by a detailed example.

AS3 BinaryConversion Utility

There are certain utility classes one would expect to have been included as part of the Flash Player API or the Flex framework, however they do not always exist.

For instance, I have been working with binary data and needed an API which would convert Decimal Numbers to their Binary equivalents, however after spending some time searching the packages on livedocs I realized that nothing had been provided. So I decided to roll my own.

The BinaryConversion utility is an all static class which will convert decimal numbers to their 4, 8, 16 or 32-bit binary equivalents, respectively. For the most part you may never need to use this API unless you need to convert decimal numbers to specific binary equivalents, however it is very useful if you need a quick Decimal to Binary conversion utility which also provides bit range validation.

You can view the BinaryConversion example as well as the source code.

BinaryConversion is protected under the MIT license.

Flex 3 ResourceInspector

Adobe Flex 3 introduces the ability to implement runtime localization via compiled resource modules. This opens up numerous possibilities for creating localized applications with Adobe Flex.

Flex Developers now have the ability to compile resources into resource modules rather than compiling the resources into the application directly. Resource modules can be preloaded for the appropriate locale when the application starts as well as loaded at runtime in order to allow switching of locales. Additionally, resources can be compiled for multiple locales into a single application or resource module.

Resources now must be accessed through the new ResourceManager (which is very similar to my original Flex 2 ResourceManager), which handles managing multiple resources for all locales.

Bindings which reference resources via the new ResourceManager automatically update if the locale changes so as to notify the components when the locale changes, allowing them to update themselves appropriately. You can also use images, sounds and so forth as resources.

Developers can programatically create resources at runtime and use them just as one would with resources which were compiled from properties files, thus allowing the ability to create resources at runtime from downloaded XML documents, service results, etc.

The ability to inspect ResourceBundles at runtime has been something which I have been specifically waiting for. This too is also available via the read-only content property on a ResourceBundle. This property can be used to retrieve the key / value pairs defined in a .properties file.

To help facilitate inspecting the contents of a ResourceBundle I have created a ResouceInspector API which provides a detailed view into a ResourceBundle. The ResouceInspector is an all static class which provides a very robust API for performing detailed inspection of the contents of a ResourceBundle.

ResouceInspector is protected under the MIT license. Check it out here.