Archive for the 'Adobe Flash' Category

Measuring code performance in ActionScript 3

Saturday, November 3rd, 2007

Adobe Flex 3 introduces the much needed, and highly welcomed Flex Profiler which allows Flex and AIR application to be thoroughly examined to measure code performance and determine potential so called “memory leaks” (not that such a thing exists - it’s called a programming error, but that’s a whole other subject in itself). Flex 3.0 provides a new profiling perspective which contains all of the tools one might expect from a high quality profiling utility. I highly recommend taking advantage of the profiler and utilizing it as a powerful addition to your Flex workflow.

Even with all of the great features available in the Profiler I still find it useful to have the ability to monitor code performance in ActionScript, especially when determining the elapsed duration of service invocations. With this in mind I developed a simple API which allows developers to measure the performance of their code as it executes; such as loops, method invocations, service invocations and so forth.

The Execution class provides an intuitive API (defined by IExecutable) from which the elapsed time of a code execution, as well as the total duration of a code execution can be measured. This can be accomplished in as little as 2 lines of code. The underlying implementation is simple and the higher level API makes it easy to use.

Typically developers should utilize the Execution API as a development aid as it is intended for use in dev environments. All references should be removed prior to an actual prod release as there is no need to compile the code into your release swf.

Below I have provided links to the Execution API resources as well as documentation which contains comprehensive use-case examples.

Execution API
IExecutable
Execution

AS3 StringTokenizer

Thursday, November 1st, 2007

One useful utility in the java.util package is the StringTokenizer class. I was looking for an ActionScript implementation the other day but was unable to locate one. So after determining the level of effort to write a StringTokenizer in ActionScript was minimal, I decided to roll my own.

The ActionScript StringTokenizer is a convenience class which provides a simple mechanism from which Strings can be extracted into individual tokens based on a specific delimiter.

StringTokenizer provides an IIterator implementation as well as an IEnumeration implementation, thus allowing a StringTokenizer to be implemented as an IIterator or IEnumeration. The interfaces are also provided with the StringTokenizer API.

Ideally a StringTokenizer is to be utilized to tokenize a String into specific tokens and is to be considered read-only. To use StringTokenizer is very simple. The constructor accepts two arguments, both of which are required. The first argument is the source String from which tokens are to be extracted. The second argument is the delimiter from which the tokens are to be based on, as in the following:

var st:StringTokenizer = new StringTokenizer("R.I.A",".");

In addition to the constructor I have provided two static factory methods for creating both the IIterator implementation and IEnumeration implementation. The factory methods require the same arguments as the constructor and are provided as an alternative to the constructor.

var it:IIterator;
it = StringTokenizer.createIterator("R.I.A",".");

// or

var enum:IEnumeration;
enum = StringTokenizer.createEnumeration("R.I.A",".");

All implementations provide operations for determining if elements (tokens) remain as well as operations for retrieving the next element.

A typical StringTokenizer implementations is as follows:

var st:StringTokenizer = new StringTokenizer("R.I.A",".");

while ( st.hasMoreTokens() )
{
   trace (st.nextToken() );
}

// outputs
// R
// I
// A

An IIterator implementation would be as follows:

var it:IIterator;
it = StringTokenizer.createIterator("R.I.A",".");

while ( it.hasNext() )
{
   trace (it.next() );
}

// outputs
// R
// I
// A

An IEnumeration implementation would be as follows

var enum:IEnumeration;
enum = StringTokenizer.createEnumeration("R.I.A",".");

while ( enum.hasMoreElements() )
{
   trace (enum.nextElement() );
}

// outputs
// R
// I
// A

In each use-case the StringTokenizer instance will return the same result as the underlying StringTokenizer implementation (e.g. invoking IIterator.next() results in a call to StringTokenizer.nextToken(), etc).

Source:
StringTokenizer
IEnumeration
IIterator

Enforcing an all static API in ActionScript 3

Friday, September 28th, 2007

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

Wednesday, September 26th, 2007

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.