Archive for the 'Design Patterns' Category

IResponder and Cairngorm

Friday, November 23rd, 2007

My original post on Cairngorm and IResponder had accidentally been deleted while updating my moderations queue, and many of you have contacted me stating that the post is no longer available so I will re-iterate what I mentioned in that post.

For some time now I have been entertaining the notion of abstracting IResponder implementations from Command classes into separate, discreet classes which are intended to handle asynchronous service invocation responses. There has been some talk in the Cairngorm community recently regarding Cairngorm Commands and IResponder implementations so I thought I would share my thoughts on the subject.

Typically most Cairngorm Events are handled by an associated Command. The Command handles the Event by updating a model on the ModelLocator, and / or instantiating a Business Delegate to manage invoking a middle-tier service.

At this point one could argue that the Command has finished doing it’s job - handling the Event. Let’s clarify by taking a look at a formal definition of the Command Pattern:

“The Command pattern is a design pattern in which objects are used to represent actions. A command object encapsulates an action and its parameters.”

From this we can deduce (in the context of a Cairngorm Event) that the Event is the “action” and the Command is the object which encapsulates the handling of the Event (action). The actual handling of the Service response could be considered a separate concern which is outside of the direct concern of the Event and Command, thus requiring an additional object to handle the service response.

However for many developers it is (by design) typical to simply have the Command implement IResponder and also handle the response from the service in addition to the actual Event. This makes sense from a convenience perspective, but not necessarily from a design perspective.

What I have been experimenting with is pretty simple and straightforward. It involves having a completely separate object implement IResponder and handle the service response directly.

Consider the following example in which a specific use-case requires an account log in. The following classes would be required: LoginEvent, LoginCommand, LoginResponder and LoginDelegate. Utilizing a separate class as the responder is very simple and straightforward and would be implemented as follows:

package events
{
  import com.adobe.cairngorm.events.CairngormEvent;
  import vo.LoginVO;

  public class LoginEvent extends CairngormEvent
  {    
    public static const LOGIN_EVENT:String="LoginEvent";
    public var vo:LoginVO;

    public function LoginEvent(vo:LoginVO)
    {
       super ( LOGIN_EVENT );
       this.vo = vo;
    }
  }
}

So far nothing different here, the above Event is just like any other CairngormEvent. Now let’s take a look at the Command implementation.

package commands
{
  import com.adobe.cairngorm.commands.ICommand;
  import com.adobe.cairngorm.events.CairngormEvent;
  import events.LoginEvent;

  public class LoginCommand implements ICommand
  {
    public function execute(event:CairngormEvent)
    {
      var evt:LoginEvent = event as LoginEvent;
      var re:IResponder = new LoginResponder();

      var delegate:LoginDelegate = new LoginDelegate(re);
      delegate.login(evt.vo.username, evt.vo.password);
    }
  }
}

Based on the above example, the only method which must be implemented is execute(), as defined by ICommand. The body of the execute() implementation instantiates an instance of LoginResponder and LoginDelegate, the LoginResponder instance is passed to the LoginDelegate as the IResponder instance.

As can be seen in the following example, the Business Delegate implementation is the same as any other typical Cairngorm Delegate:

package business
{
  import com.adobe.cairngorm.business.ServiceLocator;
  import mx.rpc.AsyncToken;
  import mx.rpc.IResponder;
  import mx.rpc.http.HTTPService;
  import vo.LoginVO;

  public class LoginDelegate
  {
    private var responder:IResponder;
    private var service:HTTPService;

    public function LoginDelegate(responder:IResponder)
    {
      this.responder = responder;
     
      var sl:ServiceLocator = ServiceLocator.getInstance();
      service = sl.getHTTPService( Services.LOGIN_SERVICE );
    }
   
    public function Login(vo:LoginVO) : void
    {
       var call:AsyncToken=service.send(vo.username,vo.password);
       call.addResponder( responder );
    }
  }
}

The IResponder implementation would be as follows:

package responders
{
  import mx.rpc.IResponder;

  public class LoginResponder implements IResponder
  {
    public function result(data:Object)
    {
      // result implementation…
    }

    public function fault(info:Object)
    {
      // fault implementation…
    }
  }
}

That’s pretty much it. Clean, simple, and yes, more code, however this design supports clean separation of concerns and promotes encapsulation and code reusability.

At the end of the day it really comes down to personal preference. For me, I always prefer to have more classes which encapsulate very specific tasks and responsibilities. As long as you have a clear and concise, but most of all, consistent design you usually can’t go wrong.

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.

Quality API Design: A how to from Google

Sunday, May 20th, 2007

As a lead Software Engineer for a large organization I spend a great deal of my time designing APIs. I spend practically the same amount of time mentoring team members and evangelizing the benefits of a good design.

If you are a programmer than you are a designer; that is, you design class hierarchies and compositional relationships, determine whether an interface or abstract is needed and so forth. This is all part of designing an API, and the more thought you give to your design the better the results will be.

Conceptually, designing a quality API is pretty straight forward: all requirements must be satisfied by the design in a clean and efficient manner. However there are many details involved which you should keep in mind when designing.

Joshua Bloch, Principle Software Engineer at Google has published a very useful article which covers the various facets of good API design. If you are a programmer this is definitely worth reading. Check it out.