Tom Sugden: Parsley Archives

February 9, 2010

The Flexible Configuration Options of Parsley

One of the nice design decisions taken by Jens Halm when he created the Parsley Application Framework was to separate the configuration mechanism from the core of the framework, so different forms of configuration can be used as required. This idea in itself is not new, since Martin Fowler advocated it in his 2004 paper, "Inversion of Control Containers and the Dependency Injection pattern":

"My advice here is to always provide a way to do all configuration easily with a programmatic interface, and then treat a separate configuration file as an optional feature. You can easily build configuration file handling to use the programmatic interface. If you are writing a component you then leave it up to your user whether to use the programmatic interface, your configuration file format, or to write their own custom configuration file format and tie it into the programmatic interface" - Martin Fowler

The application of this design principle is particularly effective in Parsley. While some frameworks are restricted to specific configuration mechanisms, Parsley provides programmatic interfaces for synchronous and asynchronous configuration, and several out-of-the-box implementations. These interfaces provide an extension-point so developers can plug-in their own configuration processors when the need arises.

Configuration Processors

In Parsley, a configuration processor uses some form of configuration data to build up a registry of object definitions. This process is abstracted by the following interfaces:

Parsley has a number of standard implementations, including the following two most commonly used:

The developer manual has a section explaining how to extend the framework with a new configuration processor:

Example: Modular Configuation Processor

There are various reasons to write a custom configuration processor. Perhaps you want to support your own particular configuration files, loaded and processed at runtime. However, these interfaces open up some other doors for more interesting forms of configuration. For example, they can be used to process configuration data from a compiled module.

Consider a large, modular application. Let's say the application consists of a Flex shell application that loads 20 modules, and 10 of these rely on the same set of shared services. It's undesirable to compile these services into the shell application, where they could be inherited by the modules, since the shell should have no knowledge of these lower level details. Instead they could be compiled into a module and the shell application could load that module at start-up, so the services are available for inheritance, but there is no dependency imposed on the shell.

This can be achieved quite simply by writing a new configuration processor, something like this:

package com.adobe
{
     import flash.events.ErrorEvent;
     import flash.events.Event;
     import flash.events.EventDispatcher;

     import mx.events.ModuleEvent;
     import mx.modules.IModuleInfo;
     import mx.modules.ModuleManager;
     import mx.utils.StringUtil;

     import org.spicefactory.parsley.core.builder.AsyncConfigurationProcessor;
     import org.spicefactory.parsley.core.builder.ConfigurationProcessor;
     import org.spicefactory.parsley.core.registry.ObjectDefinitionRegistry;

     public class ModularConfigurationProcessor 
          extends EventDispatcher 
          implements AsyncConfigurationProcessor
     {
          private static const MODULE_LOADING_ERROR : String = 
               "Unable to load the module at URL {0} due to {1}";
          private static const MODULE_INCOMPATIBLE_ERROR : String = 
               "The module doesn't implement the ConfigurationProcessor interface.";

          private var url : String;
          private var module : IModuleInfo;
          private var registry : ObjectDefinitionRegistry;

          public function ModularConfigurationProcessor( url : String )
          {
               this.url = url;
          }

          public function cancel() : void
          {
               module.removeEventListener( ModuleEvent.READY, moduleReadyHandler );
               module.removeEventListener( ModuleEvent.ERROR, moduleErrorHandler );
          }

          public function processConfiguration(
               registry : ObjectDefinitionRegistry ) : void
          {
               this.registry = registry;
               module = ModuleManager.getModule( url );
               module.addEventListener( ModuleEvent.READY, moduleReadyHandler );
               module.addEventListener( ModuleEvent.ERROR, moduleErrorHandler );
               module.load( registry.domain );
          }

          private function moduleReadyHandler( event : ModuleEvent ) : void
          {
               try
               {
                    processConfigurationWithModule();
                    dispatchEvent( new Event( Event.COMPLETE ) );
               }
               catch ( e : Error )
               {
                    dispatchErrorEvent( e.message );
               }

          }

          private function processConfigurationWithModule() : void
          {
               var instance : Object = module.factory.create();

               if ( instance is ConfigurationProcessor )
               {
                    ConfigurationProcessor( instance ).processConfiguration( registry );
               }
               else
               {
                    throw new Error( MODULE_INCOMPATIBLE_ERROR );
               }
          }

          private function moduleErrorHandler( event : ModuleEvent ) : void
          {
               dispatchErrorEvent( MODULE_LOADING_ERROR, url, event.errorText );
          }

          private function dispatchErrorEvent( message : String, ... rest ) : void
          {
               dispatchEvent( new ErrorEvent(
                    ErrorEvent.ERROR,
                    false,
                    false,
                    StringUtil.substitute( message, rest ) );
          }
     }
}

The processor is initialized with the module URL. It loads the module, creates an instance, then checks whether the module itself is a configuration processor. If so, it delegates configuration processing to the module. Here's an example module:

package com.adobe
{
    import mx.modules.ModuleBase;

    import org.spicefactory.parsley.asconfig.processor.ActionScriptConfigurationProcessor;
    import org.spicefactory.parsley.core.builder.ConfigurationProcessor;
    import org.spicefactory.parsley.core.registry.ObjectDefinitionRegistry;

    public class MyModule extends ModuleBase implements ConfigurationProcessor
    {
        public function processConfiguration(
            registry : ObjectDefinitionRegistry ) : void
        {
            new ActionScriptConfigurationProcessor(
                [ MyModuleConfiguration ] ).processConfiguration( registry );
        }
    }
}

Parsley's extension points can be taken a little further by writing a complementary configuration tag:

package com.adobe
{
    public class ModularConfig implements ContextBuilderProcessor 
    {
        public var url : String;

        public function processBuilder( builder : CompositeContextBuilder ) : void 
        {
            builder.addProcessor(
                new ModularConfigurationProcessor( url ) );
        }
    }
}

So now a modular configuration can be easily combined with other forms of Parsley configuration using the usual MXML tags:

<mx:Application ... xmlns:sf="http://www.spicefactory.org/parsley">

    <sf:ContextBuilder>
        <sf:FlexConfig type="{ MyShellApplicationConfig }"/>
        <adobe:ModularConfig url="MyModularConfig.swf"/>
        <adobe:ModularConfig url="MyOtherModularConfig.swf"/>
    </sfConfigBuilder>

    ...

</mx:Application>

Here the shell application configuration will be combined with the configuration from two modules to form a Parsley context that can be inherited by other modules, loaded later on-demand.

Conclusion

When creating a framework, it is wise to define generic interfaces for configuration processing, so that different formats can be used where appropriate. In many cases programmatic configuration with MXML is the simplest and most desirable option, but there are several valid cases for configuration from XML and other kinds of file (including SWFs) loaded at runtime. The configuration interfaces provided by Parsley satisfy this requirement very well.

Posted by tsugden at 10:25 PM | Comments (0)

November 23, 2009

Modularity in Flex Applications

There has been talk recently about the trend towards inversion-of-control frameworks in Flex. In addition to this, a higher-level movement can be seen towards modularity frameworks. Such an approach to architecture can bring many benefits, particularly in enterprise settings with larger teams and formal release processes. This post explains what modularity means in the context of Flex and discusses some of the benefits and options available for implementation.

What is Modularity?

Modularity is something more general than the Flex Module and ModuleLoader components. These are a form of modularity, but the principle is broader: modularity is about separating applications into smaller units that can be developed and deployed independently. In the context of Flex, these units might be modules, sub-applications or any other kind of encapsulated content. A modular application usually has a structure like that shown in Figure 1.

Modularity Figure.002.png

Figure 1 — The structure of a modular application

In the figure above, the application consists of a thin shell that loads three modules: Dashboard, Contacts and Messages. These modules represent different functional areas of the application. Their implementation detail is independent of one another. The application shell is responsible for loading and laying out the modules, and providing a means of communication between them. This might be a global data model, a registry of interfaces, or in the case of Figure 1, some kind of message bus.

What are the Benefits of Modularization?

Modularization can bring benefits for end-users of an application and also for the teams that develop and deliver them; Here are some of the benefits:

  • A module can be developed, tested and profiled in relative isolation.
  • Build times are shortened, since changes to one module don't require other modules or the shell application to be recompiled.
  • Modules can be loaded on demand, so the initial download for an application is smaller.
  • If a user never uses the features of one module, that module need not be loaded.
  • Individual modules can be deployed into production, instead of redeploying an entire application.
  • Different modules can be loaded for different users based on their entitlements.
  • A module is easier to understand and maintain than a monolithic application, since it is more functionally cohesion.
  • The interactions between modules can be confined to a thin API, reducing regression as an application grows.

The benefits in terms of architecture and development efficiency are arguably the most important. Small groups of developers can work on individual modules. The contracts of communication between modules can be agreed, so the implementation is free to change and improve without regression.

Framework Provisions for Modularization

Some frameworks have features to help with building modular applications. PureMVC was probably the first to do so with the multi-core version of the framework and its Pipes utility for controlled flow of messages between modules. The Parsley application framework is also designed to support modular applications, in which a module would normally have its own inversion-of-control context that inherits object definitions from the context of a shell application. Parsley includes a messaging framework that can be used for loosely-coupled communication between modules.

The other frameworks are hot on their heels. Spring Actionscript will have modular support as of version 0.9, where each module can have its own context with the option to inherit the object definitions of its parent. A parent context will be able to control which object definitions are exposed to a child context. And the lightweight Swiz framework is going to improve its support for modular development in the near future with its 1.0 release.

In addition to these established frameworks, there are some emerging frameworks focussed more specifically on modularity. Potomac and Adobe Gravity are two new frameworks inspired by OSGi, the dynamic module system for Java. Both aim to provide the infrastructure for loading bundles (i.e. modules) at runtime and communicating between them through service interfaces. Adobe Gravity remains an Adobe internal project but there are plans for a future open-source release, while Potomac is publicly available and includes some developer tooling in the form of a Flash Builder plug-in.

Cairngorm 3 and Modularization

One of the key messages of the Cairngorm 3 reference architecture (currently in draft) is to separate applications into distinct functional areas that can be developed independently; in other words a modular architecture, where each functional area is a module. The Cairngorm guidelines recommend that communication between functional areas takes place through a thin API that might consist of interfaces, events and data transfer objects. This approach minimizes dependencies between the distinct functional areas of an application. It promotes what Robert Martin terms "good dependencies" in the direction of stability. More details can be found in the Creating Functional Areas draft document.

The Enterprise Solution: Adobe LiveCycle Mosaic ES2

LiveCycle Mosaic ES2 is far more than a modularity framework, but modularity is an important part of its design. It's a client-and-server-side technology for building applications by composition, combining different pieces into personalized views that are focussed on the activities that different users perform. On the server-side, reusable application assets can be stored and shared, while LiveCycle DataServices is available for integrating with different data sources. On the client-side, applications are assembled from different tiles, that can be developed from scratch or adapted from existing Flex and HTML applications. A customizable shell application loads and lays out the tiles, and the framework provides a publish-subscribe messaging API for communication between them. For more details about the Adobe enterprise solution to modularity, refer to the LiveCycle Mosaic ES2 product page.

Conclusion

As we attempt to build bigger and better applications in Flex and AIR, the topic of modularity becomes more important to ensure efficient development, scalability and maintainability. It is vital to be able to separate portions of a large application so they can be developed, tested and deployed independently. The Flex SDK provides some simple means of modularization with Modules and Sub-Applications, and some frameworks build on top of these to provide more features. Furthermore, Adobe has now released an enterprise solution in LiveCycle Mosaic ES2 that provides the infrastructure for rapidly developing and deploying RIAs to the browser and desktop in a modular way.

Posted by tsugden at 10:32 PM | Comments (0)

August 24, 2009

Applying the Presentation Model in Flex

Introduction

The purpose of the Presentation Model design pattern is simple to grasp: it’s a way of moving state and logic out of a view component and into another class, where it can be developed, comprehended and unit tested more easily. The pattern promotes a clean separation of concerns, helping to keep MXML views as structural definitions, free from Script-block logic. However, there are several ways to apply presentation models in Flex. Some of these can help us to build simpler, more testable systems, while others may lead towards entanglement and maintenance difficulties.

For a comprehensive introduction to the Presentation Model pattern and a comparison between it and other presentation patterns, please refer to Paul Williams' blog series on the topic. At Adobe Professional Services, we have found the Presentation Model to be well suited to Flex, since it takes advantage of language features like bindings and in-line event handlers, while side-stepping some of the difficulties of unit testing display objects.

This article discusses two approaches to applying the Presentation Model -- hierarchical and componentized -- and makes a recommendation in favour of the latter.

Two Approaches: Hierarchical or Componentized

Hierarchical

With the hierarchical approach to the Presentation Model (PM) pattern, a hierarchy of PMs is developed that reflects the hierarchy of view components, as shown in the Figure 1.

PM1.png

Figure 1 - A hierarchy of views and presentation models.

Each MXML view component has a corresponding PM. The parent view contains the child views, and likewise, the parent PM contains the child PMs. Below these View-to-PM pairs, there are only basic UI controls, implemented in ActionScript without corresponding PMs.

With this approach, the top-level PM is usually instantiated in the top level view. It may be a singleton to allow other parts of the application, such as commands to access it as required. The child PMs are then passed down manually into the child views, as shown below:

<example:MyComponent ... >
<mx:Script>
[Bindable] public var model:MyComponentPM;
</mx:Script>
<example:MyChildComponent model="{ model.myChildComponentPM }" ... />
...
</example:MyComponent/>

When a hierarchy of presentation models is established, coordination takes place by method calls between the PMs, sharing objects amongst them, and dispatching events up the hierarchy. So if a user selects an item from a DataGrid in View 2, a selectedItem property may be updated on PM 2 and an event dispatched to announce the selection. PM 1 may listen to this event and perform its own logic in response.

Componentized

With the componentized approach to the Presentation Model pattern, there is a single hierarchy of view components but no hierarchy of presentation models. Each view component has a corresponding presentation model, but these models are independent of one another, as shown in Figure 2.

PM3.png

Figure 2 - A hierarchy of components, each with a presentation model

With this approach, the PMs are usually injected into their corresponding views using the view-wiring mechanism of an IoC framework. For example, the following code could be used with Parsley 2:

<example:MyComponent ... 
   addedToStage="dispatchEvent(new Event('configureIOC', true'))">
<mx:Script>
[Inject] [Bindable] public var model:MyComponentPM;
</mx:Script>
<example:MyChildComponent/>
...
</example:MyComponent/>

Here the configureIOC event instructs Parsley to inject a presentation model instance, declared in a configuration file, into the model property of the view. Notice that there is no need to pass a model into the child component. Each component is self-contained and takes care of its own business.

A variation of this approach is to declare the presentation model directly in the view, as shown below:

<example:MyComponent ... >
<example:MyComponentPM id="model"/>
<MyChildComponent/>
...
</example:MyComponent/>

Although the presentation models are kept independent of one another with the componentized approach, there remains a need to coordinate the components in some way. This can best be achieved using an Inversion-of-Control (IoC) framework, such as Parsley, Swiz or Spring ActionScript. There are ways to do so:

  • Messaging - route messages directly between the models using whatever mechanism your preferred framework provides. Parsley 2 includes a loosely-coupled messaging framework; Swiz has a notion of mediated events; while Cairngorm MVC has a singleton event dispatcher that can serve a similar purpose.
  • Domain Interfaces - inject shared domain models into multiple PMs. Coordination then takes place when the PMs call methods on the interfaces to these models, and listen for events dispatched by them. All IoC frameworks support this feature.
  • Controller/Presenter - use separate classes, known as controllers or presenters, to coordinate multiple PMs. These classes are typically injected with a number of presentation models, using an IoC framework. The controllers then listen for events and invoke methods on the PMs.

The relative merits of these are not discussed here, but will be tackled in another article. Each approach achieves a similar result of de-coupling the components from one another. The two approaches to the Presentation Model pattern are now compared in terms of their responsiveness to change.

Responsiveness to Change

It is common for the visual designs of a user interface to change during development, based on user feedback, client demands, or moments of creative inspiration from the designers. In my experience, this usually happens when I've just put the finishing touches on the implementation, the pixels are perfectly aligned and the unit tests running green! So it's important to write code in such a way as to minimize the cost of change, allowing components to be manoeuvred from place to place and logic to be reused without great effort.

Consider the case where a view component needs to move from one region of the user interface to another. Starting with the simple hierarchy shown earlier in Figure 1, changes are required to four classes, now highlighted in red in Figure 3.

PM2.png

Figure 3 - Moving part of a View-and-PM hierarchy


View 3 needs to be detached from its starting place in View 1 and re-declared in View 2. Similarly, the reference to PM 3 contained in PM 1 needs be removed and introduced to PM 2. Any coordination logic that was in PM 1 also needs to be moved into PM 2.

In contrast, the componentized approach, first shown in Figure 2, responds more easily to change. Only the declaration of View 3 needs to be moved from View 1 to View 2, as highlighted in red in Figure 4.

PM4.png

Figure 4 - Moving a component within a hierarchy

Since the logic for the View-to-PM components is self-contained and coordination takes place externally, though messaging, domain interfaces, or controller/presenters, no further changes are necessary. If test-driven development is being practiced, the unit tests for the PMs also remain intact, whereas they would need to be refactored with the hierarchical approach.

Conclusion

The Presentation Model is a useful pattern for building testable Flex applications. By moving the state and logic used to present data and handle user gestures into PMs, it can be unit tested in isolation and understood more easily than Script-block logic placed directly within views. However, rich user interfaces can be somewhat volatile, changing their shape often during development, so it is recommended to apply a componentized version of the Presentation Model that is easy to adapt, rather than developing and ultimately maintaining a hierarchy of connected presentation models.

Posted by tsugden at 9:32 PM | Comments (6)

August 11, 2009

Best Practices for the Flex Logging Framework

Introduction

The Flex Logging Framework is easy to learn and flexible to use. It supports many different scenarios, from helping developers to debug their code, to sending the details of production application errors over the wire to a remote server for monitoring. To learn the basics of the Logging Framework refer to the latest Flex Developer Guide and the Flex Logging Framework chapter of Professional Flex 3. This document describes some best practices for applying the Logging Framework on enterprise projects.

The APIs provided by the Logging Framework are simple, but they need to be used properly to get the best out of them. If care is not taken, the benefits that logging can provide for debugging and monitoring an application in production can be lost. Performance problems can even be created. This article provides a set of best practices to keep the developers in your team on the right track.

Best Practices

The following best practices are covered:

  1. Get Loggers by Class
  2. Declare Loggers as Static Constants
  3. Format Log Statements Consistently
  4. Parameterize Log Statements with Tokens
  5. Use Log Levels to Indicate Severity
  6. Use Log Filters for Focus
  7. Include Categories to Show Class Names
  8. Use Guard Conditions Appropriately
  9. Configure Logging at Runtime

Get Loggers By Class

Use a simple utility method to retrieve the logger for a particular class, instead of passing in the qualified class name as a string.

Good:

private static const LOG:ILogger = LogUtil.getLogger(MyClass);

Bad:

private static const LOG:ILogger = Log.getLogger(“my.package.MyClass”);

With the utility method approach, the class name can be refactored without needing to edit the string. Here is an implementation for the LogUtil.getLogger() method:

public static function getLogger(c:Class):ILogger 
{
    var className:String =  
        getQualifiedClassName(c).replace("::", ".")
    return Log.getLogger(className);
}

If performance profiling shows this method call to be a performance bottleneck, you may decide to revert to passing in the class name manually, since this will run a little faster. However, in most cases the convenience and refactor-ability of the above approach is the best practice.

Declare Loggers as Static Constants

In most cases, log statements apply to a particular class, so a logger should be declared as a static constant and not an instance variable.

Good:

private static const LOG:ILogger = LogUtil.getLogger(MyClass);

Bad:

private var log:ILogger = LogUtil.getLogger(MyClass);

Format Log Statements Consistently

Log statements should be formatted consistently and not haphazardly. This ensures that logging code looks professional and improves readability of log files (for humans or machines).

Good:

LOG.error(
    "Something bad has happened: event={0}, message={1}", 
    event.type, 
    message);

Bad:

LOG.error("-----------  SOMETHING BAD HAS HAPPENED!  -----------------");

Parameterize Log Statements

Parameterize log statements using the rest parameter and tokens, instead of appending strings manually. This produces cleaner code and prevents the composite string from being assembled in the event that no log target is registered.

Good:

LOG.debug(
    "Something interesting is happening: event={0}, message={1}", 
    event.type, 
    message);

Bad:

LOG.debug(
    "Something interesting is happening: event=" + 
    event.type + 
    ", message=" + 
    message);

Use Log Levels to Indicate Severity

Use the debug/info/warn/error log levels to indicate the severity of the message, instead of emphasizing important messages with special characters.

Good:

LOG.error("The service has failed and no data is available.");

Bad:

LOG.debug("!!! ERROR !!! The service has failed !!! ERROR !!!");

Use Log Filters for Focus

Set the log filters on your logging targets in order to focus on the logs produced by a certain part of the system. Do not instead try to make certain log statements stand-out with special characters. Remember to keep the format of log messages consistent.

Good:

target.filters = [ "my.important.package.MyClass" ];
target.level = LogEventLevel.INFO;
...
LOG.info("My important message");

Bad:

LOG.debug("----------- My really important message! -----------");
LOG.debug("<<<<<<<    another super important log!    >>>>>>>>");
LOG.debug("************* CAN YOU SEE ME????? ***************");

The trouble with the “special character” approach is that what is important for one developer one day is different to what is important for another developer on another day. If every developer uses their own notation for making their logs stand-out, the resulting log file becomes harder to read than when no emphasis has been placed in the text. Log levels and filters provide a more controllable and consistent mechanism for the same purpose.

Include Categories to Show Class Names

If you want to see the name of the class issuing a log statement, include categories for your log targets. Do not instead hard-code the name of the class into log statements.

Good:

target.includeCategory = true;
...
LOG.debug("Executing command");

Bad:

LOG.debug("<<<   Executing SynchronizationCommand   >>>");

The bad practice above is not refactor-safe. If the class is renamed, the message becomes confusing and if categories are included in the output, part of the message becomes redundant.

Use Guard Conditions Appropriately

Use guard conditions to prevent unnecessary processing where a log statement is expensive or nested within a loop or iteration. However, do not use guard conditions around every single log statement since this clutters up code. Decide whether or not the log statement may be expensive or use the profiler to verify this.

Good:

if (Log.isDebug())
{
    LOG.debug("Result received: {0}", ObjectUtil.toString(model));
}
for (var i:int = 0; i<10000; i++)
{
    if (Log.isDebug())
    {
        LOG.debug("Blah blah blah: i={0}", i);
    }
}

Bad:

LOG.debug("Result received: {0}", ObjectUtil.toString(model));
for (var i:int = 0; i<10000; i++)
{
   LOG.debug("Blah blah blah: i={0}", i);
   ...
}

In the bad practice above, the model will be converted into a string even if there is no registered target for the debug-level. Similarly, 10,000 log statements will be issues inside the loop regardless of whether or not there is a target registered.

Configure Logging at Runtime

Configure logging at runtime is a best practice, since it allows developers to change their log filters without rebuilding and also allows logging to be reconfigured in production without redeploying. Different log settings can even be applied to different users.

The process for configuring logging at runtime is beyond the scope of this article, however, the Parsley 2 Application Framework provides a feature for doing precisely that by loading an external XML file that specifies the targets, levels and filters. There are also examples available showing how to do the same thing using Prana/Spring ActionScript.

Posted by tsugden at 9:15 AM | Comments (2)