You are viewing the Articles in the Design Patterns Category

Quality API Design: A how to from Google

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.

AS3 Singletons, revisited

The topic of Singletons in ActionScript 3.0 has been coming up again lately and it has been very interesting to see all of the unique solutions the community has come up with. In particular I like the idea of having Singleton metadata which would allow the compiler do all of the work for us.

Personally I feel the Singleton pattern is extremely useful. It is arguably one of the most common design patterns around today. Practically every management centric API requires a Singleton one way or another. Some developers claim that the Singleton pattern is nothing more than a euphemism for a global variable, to some extent this is true, however the intent of a Singleton is clearly different.

As useful as the Singleton pattern is my biggest complaint about Singletons has always been the actual construction code required to create / protect the Singleton instance. This extra code often becomes quite verbose and it is annoying to have to sift through all of the Singleton code when working with the actual class implementation code. It would also be nice to not have to constantly re-write the Singleton construction and implementation code every time a Singleton is needed.

So is there a way around all of this? Yes!

I developed a simple class called SingletonMonitor which singleton classes can extend to allow the omission of all Singleton specific construction code. All that is needed is to have the class which is to be a Singleton extend SingletonMonitor. That’s it. No more getInstance(), inner classes, type checking and so on is needed. As a best practice I recommend that you define the Singleton instance in the class itself in order to improve code readability.

An example demonstrating how to use the SingletonMonitor can be seen in the following:

As you can see no Singleton construction code is needed. Additionally, by extending SingletonMonitor you are clearly stating that the class is intended to be a Singleton.

So how is this accomplished? It’s pretty simple…

When a derived class is instantiated the SingletonMonitor constructor is invoked, the constructor parses the current stack trace in order to determine the derived class’ name (hence the hack). The name of the derived class is then used as a key in the SingletonMonitor hash table. When a subsequent instantiation of the class is made SingletonMonitor checks the name of the class and if it has previously been defined in the hash an exception is thrown. I originally developed this using introspection to determine the fully qualified name of the class, however the preferred implementation is to have the class eagerly instantiated at compiled time (i.e. constant), thus the stack trace is not available.

Admittedly this is a bit of a hack, but so are the alternatives, otherwise this issue would never have been a topic of discussion in the first place.

However what I like about this new approach is that the Singleton is being managed outside of it’s concrete implementation, and that is the goal of this post; to present an alternative means of managing Singleton construction. Through this the Singleton construction and management code can be omitted as it is being handled by a completely separate object.

So the SingletonMonitor was the first example of how Singleton management can be achieved. The second example demonstrates the Singleton management approach implemented via composition as opposed to inheritance – which is my preferred mechanism of Singleton Management. In addition to creating the SingletonMonitor which utilizes inheritance I also created a SingletonManager which utilizes composition. The SingletonManager is the implementation I recommend and prefer.

An example demonstrating how to use the SingletonManager can be seen in the following:

The SingletonManager requires the class constructor to invoke SingletonManager.validateInstance and pass in a reference of the instance. This is automated in the SingletonMonitor as the class name is determined automatically which is convenient, however the readability of the SingletonManager is preferred as it clearly states intent. Additionally the SingletonManager guarantees the correct type is resolved.

So this is a new way of thinking about Singletons; to provide a management system from which Singleton construction and protection can consistently provided.

To be honest, this was really just an experiment I have been playing around with for some time now that I thought I should share, I am not sure if I would use the SingletonMonitor in production code as the parsing of the stack trace just feels a bit to much like a hack. However I will most likely utilize the SingeltonManager moving forward as it is a great way to abstract Singleton construction and protection from the class implementation.

My hope is that there will be a true solution available as we move forward, but for the time being if you would like to create Singletons without the need for all of the Singleton implementation code feel free to extend SingletonMonitor for management or SingletonManager for compositional management.

IResponder and Cairngorm

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 (could the Login Example have replaced Hello World?). 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:

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

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

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

The IResponder implementation would be as follows:

That’s pretty much it. Clean, simple, and yes, more code, however this design supports a clear separation of concerns and promotes encapsulation and code reusability. This example is intentionally cut and dry, however if you consider the many other possible implementations such as utilizing Dependency Injection to inject both delegates and responders, than I believe the benefits become quite clear.

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 concerns 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

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:

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:

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.

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.

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.

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:

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 Iterator API Update

I have updated the Iterator API to include a generic CollectionIterator which can be used to iterate over concrete IList implementations such as ListCollectionView, ArrayCollection and XMLListCollection.

I have also removed the abstract base implementation for all concrete Iterators in favor of the IIterator interface.

In case you are not familiar with the Iterator API, it allows developers to traverse an aggregate without the need to expose it’s underlying implementation. Developers can utilize the Iterator API to easily and intuitively iterate over Arrays, Collections and objects with the same Iterator instance. You can also implement the IIterator interface to provide additional concrete iterators in addition to the ones which I have provided; Array Iterator, Object Iterator and Collection Iterator.

A concrete Iterator can be instantiated directly or dynamically at runtime via the IteratorFactory. Typically, developers would type an iterator instance as an IIterator so as to utilize the IteratorFactory to retrieve the concrete iterator types as needed.

I have provided a simple example which contains the compiled source as well as the ASDoc and UML diagram.

source / example
ASDoc
UML