You are viewing the Articles in the Design Patterns Category

AIR SQL Framework

When working with the Adobe AIR SQL API it is important to consider the various best practices advocated by Adobe regarding performance, security and design. As there is nothing in particular in the SQL API itself to guide developers in following these best practices, developers are left to implement their own solutions, which often may vary across different applications.

For instance, consider the SQLStatement class. In order to optimize performance of the execution of a statement, the statement must first be prepared (i.e. compiled), which optimizes the statement by the runtime prior to execution. Once a statement is prepared, if the text property does not change, subsequent executions of the statement will execute faster. In order to facilitate this particular optimization developers must first be aware of this best practice, then determine the appropriate way to implement a solution in order to take advantage of the advocated practice. A simple way to facilitate this is to define separate SQLStatement instances for each unique statement which is to be executed more than once, as is suggested by Adobe, and assume the text property is not to be assigned a new value. You could take this a step further as well and define a sub class of SQLStatement which enforces the text property is only assigned a value once, thus ensuring the optimization has been set. The AIR SQL Framework provides such facilities.

The AIR SQL Framework is a simple, reusable framework which facilitates advocated best practices when working with the SQL API in AIR.

At the foundation of the AIR SQL Framework sits the following packages:

  • com.ericfeminella.sql The sql package contains a PreparedStatement class for enforcing a SQLStatement instance to only have a text value assigned during instantiation. In addition the sql package contains an ISQLStatementCache interface which can be used to indicate an implementing class is to serve as a repository of reusable PreparedStatement instances.
  • com.ericfeminella.sql.dao The DAO package provides abstractions for both synchronous and asynchronous SQL DAO implementations.
  • com.ericfeminella.sql.utils The utils package provides helper classes for substituting statement parameters and retrieving shared SQLConnection instances

This distribution of the AIR SQL Framework should be considered an alpha release as there are some additional features which I am planning to implement, namely, the addition of support for named parameter substitutions in the SQLStatementHelper class.

I have provided an example project which demonstrates a simple AIR application built utilizing the AIR SQL Framework, along with the source, binary and documentation.

AIRSQL 0.9.1

IoC and the Dependency Injection Pattern in Flex

Within the vast catalog of Design Patterns available to software developers today, one of the most important to consider when designing an enterprise class RIA is the Dependency Injection Pattern.

Dependency Injection, a term originally coined by Martin Fowler in his well known article Inversion of Control Containers and the Dependency Injection Pattern, is a more specific term for what is otherwise known as Inversion of Control or IoC.

Fowler’s assessment of Inversion of Control containers concluded that the name itself – Inversion of Control – was too generic, thus as a result from his discussions with various IoC advocates they settled on the more specific term Dependency Injection, also known as DI for short. The terms Inversion of Control (IoC) and Dependency Injection (DI) are commonly used interchangeably to describe the same underlying design principle of separating configuration from implementation.

There are three basic forms of Dependency Injection, which are generally referred to as type 1 IoC (Interface Injection), type 2 IoC (Setter Injection) and type 3 IoC (Constructor Injection). Before diving into the specifics of how to implement the various forms of DI, I will first discuss what Dependency Injection is on a conceptual level as well as what each specific form means. The examples outlined here are in ActionScript 3, however it is important to keep in mind that like most Design Patterns Dependency Injection applies to any language which supports an Object Oriented Model.

At the most basic level Dependency Injection can be explained as a way of decoupling classes from their dependencies by injecting the dependencies into them rather than having the classes directly reference specific implementations. A class which directly references other classes is coupled to those classes – these are the dependencies. However a class which does not reference any other classes would probably not be very useful. At some point the dependencies need to be made. Dependency Injection is a solution to how those dependencies are made, and the manner by which they are provided.

For example, consider the following class which illustrates a typical example of a class’s dependency on another class:

From looking at the code above the dependencies are pretty obvious; the ConfigurationManager class is dependent on the XMLConfiguration class. Now this type of dependency is quite typical so at this point you may be asking what is wrong with doing this?

The first problem is that the config property is defined as a concrete implementation:

This violates a fundamental OO principle:

Program to interfaces, not implementations.

More importantly and perhaps pertinent to the topic at hand is that it also isn’t very hard to imagine that at some point we may want to load a configuration from some other means, such as a properties file, a remote service and so on. In order to do so we would need to modify the class, and from this we can deduce that the class does not scale very well.

So we could begin improving our current implementation by simply refactoring the ConfigurationManager class to define the config property as an abstraction, say IConfiguration:

As you can see this is certainly a step in the right direction, however the underlying problem still remains; we are still instantiating an instance of XMLConfiguration directly in the ConfigurationManager – and that is exactly what Dependency Injection is all about: providing a solution to the recurring problem of managing dependencies between classes, and how those dependencies are provided.

When implementing the Dependency Injection Pattern in an application you do so by creating a context (configuration) which defines all dependencies in an application as well as an Assembler which is responsible for assembling the mappings and associations between objects and their dependencies. This is done by utilizing any combination of the three forms of DI; Interface Injection, Setter Injection and Constructor Injection. Below is a brief description of each form:

Interface Injection
Interface Injection is the process by which all dependencies are injected into an object via an interface. For example, the ConfigurationManager example above could implement an interface which defines the operations needed to inject the appropriate Configuration implementation.

Setter Injection
Setter injection as you may have guessed is the process of injecting dependencies via public setters; both explicit or implicit. Using Setter Injection the ConfigurationManager could provide public setters from which an Assembler could inject the appropriate Configuration implementation.

Constructor Injection
Again as you may have guessed Constructor Injection is the process of injecting dependencies via arguments in the class constructor. Using Constructor Injection the concrete Configuration could just as easily be injected.

Both Constructor and Setter Injection are by far the preferred forms of Dependency Injection. Interface Injection has some major drawbacks as it somewhat leads to convoluted code since multiple additional interfaces need to be defined and implemented. The fact that “special” types need to be created and implemented in order to facilitate DI using Interface Injection greatly limits the potential for its use.

There are numerous frameworks for various platforms which provide out of the box Dependency Injection implementations for all three forms of DI. All of these frameworks handle the wiring necessary for easily implementing Dependency Injection in an application, the most notable being the Spring Framework for Java/J2EE. There are also quite a few DI solutions for Flex and ActionScript applications as well. Optionally you could choose to roll your own however I would first suggest investigating some of the frameworks which are currently available as they more than likely provide what you need. The Prana Framework by Christophe Herreman is a good choice as it is one of the most prevalent DI solution available at the moment for Flex.

Using the ConfgurationManager example from above I have provided a basic example application which demonstrates how to implement Dependency Injection utilizing the Prana framework. The example application uses constructor injection to provide a concrete Configuration to the ConfigurationManager, however I encourage you to experiment with the other mechanisms of injection as well. The example is intentionally kept very simple in that it is only intended to convey the basic concepts of DI and how to use it in Flex with Prana, from this you should have a good understanding of how to implement DI in a larger context.

Cairngorm moving forward

This week Adobe announced that Cairngorm has been moved to from Labs to opensource.adobe.com.

So what does this mean for you, as a developer, building RIAs targeting the Adobe Flex platform on top of Cairngorm?

It means a lot.

The most significant being that Cairngorm now has a formal community based initiative. This in itself facilitates positive growth as it encourages community feedback and collaboration. It allows the community to have an open podium for discussion, collaboration and most important, knowledge sharing.

So how can you contribute? To begin, start by signing up as a member and sharing your thoughts and experiences. Get involved; engage in conversations with the rest of the community. Take a look under the hood; get to know Cairngorm internals (if you don’t already).

I have a lot of confidence in the future of Cairngorm and I think we can all expect good things to come.

Let design guide, not dictate

A good design should intend to guide implementation, not dictate it; and for good reason as, the dynamic nature of requirements and systems is often too complex to view for a technical design to be considered as anything more than a basic prescription intended to convey the basis for implementation. Yet far too often people seem to believe that once a detailed design has been completed and approved implementation should be a breeze; however, this is just not a very realistic expectation.

For instance, one of my core job responsibilities is to review technical design documents and provide feedback and direction. This is an iterative process which typically has between 1-3 iterations depending on the complexity of the system. Initially myself and an engineer are given requirements for review. He or she then begins an initial draft of the design and once completed passes it on to me for review. I then review the document and provide feedback where applicable, either via annotations to the document itself or by reviewing with the developer (which is by far my preferred process). Should modifications be required the developer will then make revisions as needed. This process is repeated (within practicality) until final design has been approved.

At first it may appear as if only a single design iteration and review would be needed, however more often than not, requirements may not be completely understood during the beginning stages of design, nor are they typically ever set in stone so it is very common that a design will need to change during the early stages of a project or even throughout the entire development stage. Once final design has been completed an engineer then begins implementing the design. Theoretically this may appear to be a quite simple process: create a great design which contains as much detail as possible, review it, make revisions and approve it, then just pass it off to any developer for implementation and that’s it, done, right? – wrong!

There are a number of problems to this approach. Below I have outlined the three I feel are most significant and the solutions I have found to address each.

Creativity

The first problem is that a design which goes into too much detail completely limits or even worse, kills creativity – which in my opinion is the single most important trait a developer can possess, especially when designing. The developer is now merely a typist and will undoubtedly become very bored when implementing the design, especially if it is not even his/her design to begin with! Because of this lack of creativity the final code will ultimately suffer and bugs can be expected. Keeping design on a higher level allows developers to have the creative freedom needed to provide quality implementations and work they can feel is their own.

Flexibility

The second problem is that the more detailed and precise the design the less flexibility there is when requirements change and modifications need to be made to the design and thus implementation. For example, if a design contains very low level details, such as method signatures and other implementation specific details the ability to change the design now becomes increasingly complex and will result in much of the design needing to be reworked significantly. In addition the more detail there is the harder it is to write unit tests against the design as the actual implementation has already been defined. Designs need to be very high level and should not go beyond identifying class names, their responsibilities, relationships and dependencies.

Tools

The third problem is that far too often developers get caught up in all the details of UML notation and related tools. Again, this negates creativity and results in the developer concentrating more on making the design look technically correct rather than concentrating on designing towards a great solution which addresses the problem at hand. In addition, this also results in unnecessary time being spent to complete the design – time which otherwise could have been much better spent on something that produces a better pay off for the project. Now this is not to say that UML shouldn’t be used, actually quite the contrary as I feel a final design should be in UML (or some other format) as a shared language is very helpful in allowing readers to easily understand the design. I always suggest a technique where developers draw out their design in any way that makes sense to them without having to give much thought to anything other than the solution itself. This could be anything from drawing / scribbling thoughts on a pad, to building out a vision from legos – seriously! Only once the design has been envisioned would I recommend bringing it to realization through the use of a formal design tool, such as Visio or other UML tools to be used.

The above illustrates the three most common design issues I have encountered, most of which pertain to over-detailed designs, as well as the approach I take to address each. If you have not encountered any of these issues in your own work than that is generally a good sign, however try to keep them in mind when designing as it will pay off in the end. The important thing to remember when designing is to design for flexibility and simplicity. Less is usually more and the KISS principle, especially when applied to software design, will always pay off in the end.

Principle of Least Knowledge

One very important (yet often overlooked) design guideline which I advocate is the Principle of least knowledge.

The Principle of Least knowledge, also known as The law of Demeter, or more precisely, the Law of Demeter for Functions/Methods (LoD-F) is a design principle which provides guidelines for designing a system with minimal dependencies. It is typically summarized as “Only talk to your immediate friends.”

What this means is a client should only have knowledge of an objects members, and not have access to properties and methods of other objects via the members. To put it in simple terms you should only have access to the members of the object, and nothing beyond that. Think if it like this: if you use more than 1 dot you are violating the principle.

Consider the following: We have three classes: ClassA, ClassB and ClassC. ClassA has an instance member of type ClassB. ClassB has an instance member of type ClassC. This can be designed in such a way which allows direct access all the way down the dependency chain to ClassC or beyond, as in the following example:

The above example is quite common, however it violates The Principle of Least Knowledge as it creates multiple dependencies, thus reducing maintainability as should the internal structure of ClassA need to change so would all instances of ClassA.

Now keep in mind that in all software development there are trade-offs to some degree. Sometimes performance trumps scalability or vice-versa, other times readability trumps both. A perfect example of where you would not want to use The Principle of Least Knowledge is in a Cairngorm ModelLocator implementation. The Cairngorm ModelLocator violates the Principle of least knowledge for good reason – it simply would not be practical to write wrapper methods for every object on the ModelLocator. This is the main drawback of the Principle of least Knowledge; the need to create wrapper methods for each object, which are more formally known as Demeter Transmogrifiers.

The goal of good software design is to minimize dependencies, and by carefully following the guidelines provided by The Principle of Least Knowledge this becomes much easier to accomplish.

API Design: Method parameter objects

When defining a constructor or method with more than three parameters it is considered a best practice to create a parameters object for holding the values which are required. This especially holds true when some of the parameters are optional (as they will contain default values) and also when two or more consecutive parameters are of the same type (as developers may accidentally transpose these parameters – which will not result in compile time or runtime errors, making debugging a nightmare!)

The most appropriate solution for such cases is to break up the method into separate methods, however when this is not feasible creating a parameters object will improve both code readability and provide a cleaner design which leaves less room for unexpected errors.

Consider the following method:

The parameters defined in this method are typical of what you will often see, however it is much cleaner and reliable to create a parameters object for holding these parameters. In addition, a parameters object allows for a much easier client implementation as default values need not be reassigned for all parameters which proceed a parameter which you need to specify a value other than the default value. For instance, if a method accepts 5 parameters and the first two parameters are required but the last three are optional, if you you need to specify a value for the last parameter you will need to re-assign the default values for the proceeding parameters, when in fact you really only need to specify three parameters.

The following example demonstrates creating a parameter object which can be passed to “someMethod”:

When invoking “someMethod” clients can now simply instantiate an instance of the parameter object, set values only for what is needed and pass it in as follows:

So if you would like to improved code readability and provide proactive exception precautions, consider utilizing parameter objects for methods which require more than three parameters.