<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Tom Sugden</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/" />
    <link rel="self" type="application/atom+xml" href="http://blogs.adobe.com/tomsugden/atom.xml" />
   <id>tag:blogs.adobe.com,2009:/tomsugden//142</id>
    <link rel="service.post" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142" title="Tom Sugden" />
    <updated>2009-09-29T13:08:49Z</updated>
    
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.261</generator>
 

<entry>
    <title>Vote for Morgan Stanley Matrix!</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/09/vote_for_morgan_stanley_matrix.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=43232" title="Vote for Morgan Stanley Matrix!" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.43232</id>
    
    <published>2009-09-29T12:59:03Z</published>
    <updated>2009-09-29T13:08:49Z</updated>
    
    <summary>Morgan Stanley Matrix has reached the finals for a MAX Award in the Enterprise Productivity category. You can view the vignettes and cast your vote at: http://max.adobe.com/awards/finalists/ Public voting has started and the voting will be live until Tuesday, October...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>Morgan Stanley Matrix has reached the finals for a MAX Award in the Enterprise Productivity category. You can view the vignettes and cast your vote at:</p>

<ul>
	<li><a href="http://max.adobe.com/awards/finalists/">http://max.adobe.com/awards/finalists/</a></li>
</ul>

<p>Public voting has started and the voting will be live until Tuesday, October 6, when the winners will be announced at the event. For more info about Morgan Stanley Matrix, see my <a href="http://blogs.adobe.com/tomsugden/2009/09/morgan_stanley_matrix_at_max.html">earlier blog post</a> or come to the <em>Building Morgan Stanley Matrix</em> session at MAX next week.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Morgan Stanley Matrix at MAX</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/09/morgan_stanley_matrix_at_max.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=43027" title="Morgan Stanley Matrix at MAX" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.43027</id>
    
    <published>2009-09-21T20:40:05Z</published>
    <updated>2009-09-21T21:11:02Z</updated>
    
    <summary>Next month at Adobe MAX 2009 in Los Angeles, Børre Wessel (Lab49) and myself will be presenting Matrix, the next-generation sales and trading platform from Morgan Stanley....</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Flex" />
    
        <category term="General" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>Next month at <a href="http://max.adobe.com/">Adobe MAX 2009</a> in Los Angeles, <a href="http://www.borrewessel.com/">Børre Wessel</a> (<a href="http://lab49.com/">Lab49</a>) and myself will be presenting Matrix, the next-generation sales and trading platform from Morgan Stanley. </p>]]>
        <![CDATA[<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="ms-matrix-1.jpg" src="http://blogs.adobe.com/tomsugden/2009/09/21/ms-matrix-1.jpg" width="383" height="373" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /></span></p>

<p>The session is entitled, "Building Matrix – Scaling Flex for a Large Trading Application" and it will cover our experiences as we worked on the client-side architecture of Matrix, together with a large team of developers. We will discuss the patterns and practices that made the delivery possible &mdash; modularization, dependency management, performance tuning, inversion-of-control, etc. &mdash; and the challenges we faced along the way, providing guidance for other large-scale enterprise Flex projects.</p>

<p>For more information, put on your headphones and check out the <a href="http://www.morganstanley.com/matrixinfo/">Morgan Stanley Matrix micro-site</a>. Some other resources are listed below. Hope to see you there!</p>

<ul>
	<li><a href="http://www.ashorten.com/2009/06/09/morgan-stanley-raises-the-bar-for-rich-internet-applications-using-adobe-flash-platform-technologies/">Morgan Stanley raises the bar for rich Internet applications using Adobe Flash Platform technologies</a></li>
<li><a href="http://www.readwriteweb.com/archives/morgan_stanleys_matrix_an_app_from_the_future.php">Morgan Stanley's Matrix: An App From the Future</a></li>
<li><a href="http://www.finextra.com/fullstory.asp?id=20114">Morgan Stanley taps Adobe Flex framework for new trading platform</a></li>
</ul>]]>
    </content>
</entry>

<entry>
    <title>Coming Soon: Cairngorm 3</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/09/coming_soon_cairngorm_3_1.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=42889" title="Coming Soon: Cairngorm 3" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.42889</id>
    
    <published>2009-09-13T19:57:30Z</published>
    <updated>2009-09-13T20:02:13Z</updated>
    
    <summary>Cairngorm is about to undergo a transformation that will broaden its scope and increase its value to clients and partners. Instead of centering around a specific implementation of the Model-View-Controller pattern, Cairngorm 3 will consist of a set of best...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Cairngorm" />
    
        <category term="Flex" />
    
        <category term="Frameworks" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>Cairngorm is about to undergo a transformation that will broaden its scope and increase its value to clients and partners. Instead of centering around a specific implementation of the Model-View-Controller pattern, Cairngorm 3 will consist of a set of best practices, tools and libraries, many of which apply across frameworks. This is the knowledge gathered by the Adobe Technical Services organization and partners over the last five or six years, condensed and presented to help others to deliver successful Flex projects in the enterprise.</p>]]>
        <![CDATA[<p>For those familiar with the Cairngorm 1 & 2 micro-architecture, the traditional Cairngorm library remains a part of Cairngorm 3. Our best practices for applying the Cairngorm library will be shared, together with information about tried-and-tested extensions. And like before, Cairngorm 3 will recommend a layered architecture that separates concerns and supports test-driven development, but this time the approach has been refined and most parts of it complement multiple frameworks.</p>

<p>So what is Cairngorm now if it isn’t just a framework? Well it’s a foundation for delivering successful Flex projects. It’s the answer to the question, “What are the best practices for Flex in the enterprise?”, to help set new teams off on the right track. It’s the information that can’t always be found in official documentation or framework manuals. It's going to be accessible, informative and open-source. And it’s coming soon...</p>]]>
    </content>
</entry>

<entry>
    <title>Eliminate Common Bad Practices with FlexPMD</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/09/eliminate_common_bad_practices.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=42718" title="Eliminate Common Bad Practices with FlexPMD" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.42718</id>
    
    <published>2009-09-04T06:21:51Z</published>
    <updated>2009-09-04T06:56:50Z</updated>
    
    <summary>Adobe Technical Services are pleased to release FlexPMD to the community. FlexPMD is a new open-source tool for improving code quality. It works by analyzing ActionScript and MXML source files to identify common bad practices, like over-long classes or functions,...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Flex" />
    
        <category term="FlexPMD" />
    
        <category term="General" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>Adobe Technical Services are pleased to release <a href="http://opensource.adobe.com/wiki/display/flexpmd/FlexPMD">FlexPMD</a> to the community. FlexPMD is a new open-source tool for improving code quality. It works by analyzing ActionScript and MXML source files to identify common bad practices, like over-long classes or functions, reliance on magic strings, unused parameters, and many other programming mistakes or misjudgments. It can even spot code that might be causing performance problems, and furthermore, the ruleset can be customized and extended, to include rules specific to the coding conventions of your own project.</p>]]>
        <![CDATA[<ul>
	<li><a href="http://opensource.adobe.com/svn/opensource/flexpmd/bin/flex-pmd-ruleset-creator.html">View the current ruleset in a handy Flex application</a></li>
</ul> 

<p>FlexPMD can be launched from the command line, but the best practice is to invoke it from your Ant or Maven continuous integration build scripts. In this case, a report will be generated each time a build is performed, describing the violations of your chosen ruleset. As soon as someone checks in their fancy new 1,000 line algorithm with nested loops, numeric variable names and a gaggle of change-watchers, the red flag will be raised. The report produced by Flex PMD allows simple coding mistakes to be identified and corrected immediately, when the cost is far cheaper than attempting to refactor a system that has been decaying for months. <br />
                                                        <br />
<span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="FlexPMDReport.jpg" src="http://blogs.adobe.com/tomsugden/2009/09/04/FlexPMDReport.jpg" width="572" height="336" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /><center><em>Figure 1: A Sample FlexPMD Report</em></center><br />
</span></p>

<p>Another benefit of FlexPMD is that code reviews become more valuable. Since FlexPMD can automatically identify the common problems, code reviewers are left to reflect on the deeper issues, like domain modeling, separation of concerns, proper encapsulation, and so on. </p>

<p>To find out more about FlexPMD and start using it on your own projects, follow these links to Adobe Open Source:</p>

<ul>
	<li><a href="http://opensource.adobe.com/wiki/display/flexpmd/About">About FlexPMD</a> </li>
	<li><a href="http://opensource.adobe.com/wiki/display/flexpmd/Downloads">Download FlexPMD</a> </li>
	<li><a href="http://opensource.adobe.com/wiki/display/flexpmd/How+to+invoke+FlexPMD">How To Invoke FlexPMD</a></li>
	<li><a href="http://opensource.adobe.com/wiki/display/flexpmd/How+to+interpret+results">How To Interpret FlexPMD Results</a> </li>
	<li><a href="http://opensource.adobe.com/wiki/display/flexpmd/How+to+interpret+results">How to Add Your Own Rule</a></li>
</ul>

<p>Credit goes to <a href="http://blogs.adobe.com/xagnetti/">Xavier Agnetti</a> for conceiving and leading this effort, with support and contributions from many in the Technical Services organization and other parts of Adobe.</p>]]>
    </content>
</entry>

<entry>
    <title>Applying the Presentation Model in Flex</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/08/applying_the_presentation_mode.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=42495" title="Applying the Presentation Model in Flex" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.42495</id>
    
    <published>2009-08-24T20:32:51Z</published>
    <updated>2009-08-26T09:41:57Z</updated>
    
    <summary>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...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Flex" />
    
        <category term="Frameworks" />
    
        <category term="Parsley" />
    
        <category term="Patterns" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p><big>Introduction</big></p>

<p>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.</p>

<p>For a comprehensive introduction to the Presentation Model pattern and a comparison between it and other presentation patterns, please refer to <a href="http://blogs.adobe.com/paulw/archives/2007/10/presentation_pa_3.html">Paul Williams' blog series</a> 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.</p>

<p>This article discusses two approaches to applying the Presentation Model -- hierarchical and componentized -- and makes a recommendation in favour of the latter.</p>]]>
        <![CDATA[<p><big>Two Approaches: Hierarchical or Componentized</big></p>

<p><strong>Hierarchical</strong></p>

<p>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.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="PM1.png" src="http://blogs.adobe.com/tomsugden/2009/08/24/PM.018.png" width="330" height="274" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /><br />
<center><strong>Figure 1 - A hierarchy of views and presentation models.</strong></center><br />
</span></p>

<p>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. </p>

<p>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:</p>

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

<p>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.</p>

<p><strong>Componentized</strong></p>

<p>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.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="PM3.png" src="http://blogs.adobe.com/tomsugden/2009/08/24/PM.020.png" width="330" height="272" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /><center><strong>Figure 2 - A hierarchy of components, each with a presentation model<br />
</strong></center></span></p>

<p>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:</p>

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

<p>Here the <em>configureIOC</em> event instructs Parsley to inject a presentation model instance, declared in a configuration file, into the <em>model</em> 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. </p>

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

<pre>
&lt;example:MyComponent ... &gt;<br/>
   &lt;example:MyComponentPM id="model"/&gt;<br/>
   &lt;MyChildComponent/&gt;<br/>
   ...<br/>
&lt;/example:MyComponent/&gt;
</pre>

<p>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:</p>

<ul>
	<li><em>Messaging</em> - 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.</li>
	<li><em>Domain Interfaces</em> - 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.</li>
	<li><em>Controller/Presenter</em> - 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.</li>
</ul>

<p>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.</p>

<p><big>Responsiveness to Change</big></p>

<p>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.</p>

<p>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.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="PM2.png" src="http://blogs.adobe.com/tomsugden/2009/08/24/PM.019.png" width="330" height="359" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /><center><strong>Figure 3 - Moving part of a View-and-PM hierarchy</strong></center></span></p>

<p><br />
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.</p>

<p>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.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="PM4.png" src="http://blogs.adobe.com/tomsugden/2009/08/24/PM.021.png" width="330" height="361" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /><center><strong>Figure 4 - Moving a component within a hierarchy</strong></center></span></p>

<p>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.</p>

<p><strong>Conclusion</strong></p>

<p>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.</p>]]>
    </content>
</entry>

<entry>
    <title>Best Practices for the Flex Logging Framework</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/08/best_practices_for_the_flex_lo.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=42231" title="Best Practices for the Flex Logging Framework" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.42231</id>
    
    <published>2009-08-11T08:15:34Z</published>
    <updated>2009-08-11T08:41:59Z</updated>
    
    <summary>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...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Flex" />
    
        <category term="Logging" />
    
        <category term="Parsley" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<h2>Introduction</h2>

<p>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 <a href="http://www.amazon.com/Professional-Adobe-Flex-Wrox-Programmer/dp/0470223642/ref=sr_1_1?ie=UTF8&s=books&qid=1249979369&sr=8-1">Professional Flex 3</a>. This document describes some best practices for applying the Logging Framework on enterprise projects.</p>

<p>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.<br />
</p>]]>
        <![CDATA[<h2>Best Practices</h2>

<p>The following best practices are covered:</p>

<ol>
	<li>Get Loggers by Class</li>
	<li>Declare Loggers as Static Constants</li>
	<li>Format Log Statements Consistently</li>
	<li>Parameterize Log Statements with Tokens</li>
	<li>Use Log Levels to Indicate Severity</li>
	<li>Use Log Filters for Focus</li>
	<li>Include Categories to Show Class Names</li>
	<li>Use Guard Conditions Appropriately</li>
	<li>Configure Logging at Runtime</li>
</ol>

<h2>Get Loggers By Class</h2>

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

<p>Good:</p>

<pre>
private static const LOG:ILogger = LogUtil.getLogger(MyClass);
</pre>

<p>Bad:</p>

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

<p>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:</p>

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

<p>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. </p>

<h2>Declare Loggers as Static Constants</h2>

<p>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.</p>

<p>Good:</p>

<pre>
private static const LOG:ILogger = LogUtil.getLogger(MyClass);
</pre>

<p>Bad:</p>

<pre>
private var log:ILogger = LogUtil.getLogger(MyClass);
</pre>
<br/>
<h2>Format Log Statements Consistently</h2>

<p>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).</p>

<p>Good:</p>

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

<p>Bad:</p>

<pre>
LOG.error("-----------  SOMETHING BAD HAS HAPPENED!  -----------------");
</pre>
<br/>
<h2>Parameterize Log Statements</h2>

<p>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.</p>

<p>Good:</p>

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

<p>Bad:</p>

<pre>
LOG.debug(
    "Something interesting is happening: event=" + 
    event.type + 
    ", message=" + 
    message);
</pre>
<br/>
<h2>Use Log Levels to Indicate Severity</h2>

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

<p>Good:</p>

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

<p>Bad:</p>

<pre>
LOG.debug("!!! ERROR !!! The service has failed !!! ERROR !!!");
</pre>
<br/>
<h2>Use Log Filters for Focus</h2>

<p>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.</p>

<p>Good:</p>

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

<p>Bad:</p>

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

<p>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.</p>

<h2>Include Categories to Show Class Names</h2>

<p>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.</p>

<p>Good:</p>

<pre>
target.includeCategory = true;
...
LOG.debug("Executing command");
</pre>

<p>Bad:</p>

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

<p>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.</p>

<h2>Use Guard Conditions Appropriately</h2>

<p>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.</p>

<p>Good:</p>

<pre>
if (Log.isDebug())
{
    LOG.debug("Result received: {0}", ObjectUtil.toString(model));
}
</pre>

<pre>
for (var i:int = 0; i<10000; i++)
{
    if (Log.isDebug())
    {
        LOG.debug("Blah blah blah: i={0}", i);
    }
}
</pre>

<p>Bad:</p>

<pre>
LOG.debug("Result received: {0}", ObjectUtil.toString(model));
</pre>

<pre>
for (var i:int = 0; i<10000; i++)
{
   LOG.debug("Blah blah blah: i={0}", i);
   ...
}
</pre>

<p>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.</p>

<h2>Configure Logging at Runtime</h2>

<p>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. </p>

<p>The process for configuring logging at runtime is beyond the scope of this article, however, the <a href="http://www.spicefactory.org/parsley/">Parsley 2 Application Framework</a> 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.</p>]]>
    </content>
</entry>

<entry>
    <title>A Declarative Approach to Flex Popups</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/07/a_declarative_approach_to_flex.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=11452" title="A Declarative Approach to Flex Popups" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.11452</id>
    
    <published>2009-07-18T21:07:34Z</published>
    <updated>2009-07-21T16:46:46Z</updated>
    
    <summary>Yaniv De Ridder and myself have developed a small Flex library for opening and closing popups. Instead of using the PopUpManager directly and writing script-block logic to manage their creation and removal, a pair of simple MXML tags are available...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Components" />
    
        <category term="Flex" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p><a href="http://blogs.adobe.com/yderidder">Yaniv De Ridder</a> and myself have developed a small Flex library for opening and closing popups. Instead of using the <tt>PopUpManager</tt> directly and writing script-block logic to manage their creation and removal, a pair of simple MXML tags are available for declaring within view components. Here's the "Hello World" of declarative popups:</p>

<pre>
&lt;popup:PopUpWrapper open="{model.openPopUp}"&gt;
   &lt;mx:Label text="Hello World"/&gt;
&lt;/popup:PopUpWrapper&gt;
</pre>

<p>The <tt>PopUpWrapper</tt> tag is a non-visual component that manages opening and closing the popup. When its <tt>open</tt> property is set to true, a popup is opened containing the component wrapped by the tag; in this case a <tt>Label</tt>. When the <tt>open</tt> property is set back to false, the popup closes again. Alternatively, the component may dispatch an <tt>Event.CLOSE</tt> event, which will be handled by the <tt>PopUpWrapper</tt> itself.</p>

<p>This approach helps to keep MXML views components clean and free from ActionScript logic, whilst removing duplicated code wherever the <tt>PopUpManager</tt> is needed. The opening and closure can be controlled conveniently through bindings, as above, which plays nicely with <a href="http://martinfowler.com/eaaDev/PresentationModel.html">presentation models</a>. There are also simple ways to control the life-cycle of the popup and to apply special behaviors, such as effects that play while it opens and closes.</p>

<p>The remainder of this post covers the two components available -- <tt>PopUpWrapper</tt> and <tt>PopUpFactory</tt> -- explaining the differences between them. The library, source code, unit tests and a sample application are available for download here:</p>

<ul>
<li><tt><a href="http://blogs.adobe.com/tomsugden/2009/07/19/FlexPopUpWrapper.swc">FlexPopUpWrapper.swc</a></tt> - the SWC library compiled with Flex 3.3.</li>
<li><tt><a href="http://blogs.adobe.com/tomsugden/2009/07/19/FlexPopUpWrapper.zip">FlexPopUpWrapper</a></tt> - a Flex library project containing the source for the two components.</li>
<li><tt><a href="http://blogs.adobe.com/tomsugden/2009/07/19/FlexPopUpWrapperExample.zip">FlexPopUpWrapperExample</a></tt> - a Flex application project containing a sample application.</li>
<li><tt><a href="http://blogs.adobe.com/tomsugden/2009/07/19/FlexPopUpWrapperUnitTests.zip">FlexPopUpWrapperUnitTests</a></tt> - a Flex application project containing the unit test runner for the FlexPopUpWrapper library.</li>
</ul>
]]>
        <![CDATA[<h2>Using Declarative Popups</h2>

<p>There are two components with slightly different capabilities:</p>

<ul>
<li><tt>PopUpWrapper</tt> - this is the simplest tag. It defers the creation of the popup view until the first time the popup is opened, then reuses the same view every subsequent time. There is no mechanism for releasing that view to be garbage collected.</li>
<li><tt>PopUpFactory</tt> - this is the more flexible but less simple tag. It also defers creation of the popup view, but gives control over whether or not the view should be reused when the popup is next opened. If reuse is disabled, the view is made eligible for garbage collection upon closure.</li>
</ul>

<p>Some examples of each are now provided.</p>

<p><b>The PopUpWrapper Component</b></p>

<p>Here's a more detailed version of the "Hello World", this time showing all of the properties and events available:</p>

<pre>
&lt;popup:PopUpWrapper
    open="{model.openPopUp}"
    center="true"
    modal="false"
    childList="{PopUpManagerChildList.POPUP}"
    opening="openingHandler()"
    opened="openedHandler()"
    closing="closingHandler()"
    closed="closedHandler()"&gt;
    &lt;mx:Label text="Hello World!"/&gt;
&lt;popup:PopUpWrapper&gt;
</pre>

<p>The properties provide the same control over the popup as the <tt>PopUpManager</tt>. The events are dispatched at various points during the life-cycle of a popup:</p>

<ul>
<li><tt>PopUpEvent.OPENING</tt> is dispatched after the popup view has been created but just before it has actually been added to the display list. </li>
<li><tt>PopUpEvent.OPENED</tt> is dispatched just after the popup view has been added to the display list.</li>
<li><tt>PopUpEvent.CLOSING</tt> is dispatched just before the popup view is removed from the display list.</li>
<li><tt>PopUpEvent.CLOSED</tt> is dispatched just after the popup view has been removed from the display list.</li>
</ul>

<p>Here's another example where the popup is opened or closed using buttons instead of binding. The view used for the actual popup is a custom component.</p>

<pre>
&lt;popup:PopUpWrapper id="popup"&gt;
    &lt;mypopup:MyPopupView/&gt;
&lt;/popup:PopUpWrapper&gt;

&lt;mx:Button label="Open" click="popup.open = true"/&gt;
&lt;mx:Button label="Close" click="popup.open = false"/&gt;
</pre>

<p>The popup view itself can also instruct the closure of the popup by dispatching an <tt>Event.CLOSE</tt> event. For example:</p>

<pre>
&lt;mypopup:VBox ... &gt;
    &lt;mx:Label text="My Popup!"/&gt;
    &lt;Button 
        label="Close" 
        click="dispatchEvent(new Event(Event.CLOSE))"/&gt;
&lt;/mypopup:VBox&gt;    
</pre>

<p><b>The PopUpFactory Component</b></p>

<p>The <tt>PopUpFactory</tt> tag uses a different mechanism for specifying the popup view. It is in fact the same approach that list-based controls use for their item renderers. The factory property can either be set to the class name for the popup view, or else an in-line component can be declared.</p>

<p>Here is a simples use case, specifying the popup view class name:</p>

<pre>
&lt;popup:PopUpFactory 
    open="{model.openPopUp}"
    factory="my.package.MyPopupView"
    reuse="false"/&gt;
</pre>

<p>Notice that the <tt>PopUpFactory</tt> includes a reuse property. This gives control over whether or not the popup view is reused, in contrast to the <tt>PopUpWrapper</tt> tag which always reuses the view and never makes it eligible for garbage collection. </p>

<p>When working with the <tt>PopUpManager</tt> directly it is common to make popups eligible for garbage collection once they have been removed. However there are good use cases for both approaches. If an application shows a large popup at start-up and then never again, it is wasteful of resources to keep it in memory. Alternatively, if a popup is repeatedly shown and hidden, such as a context menu, it is more efficient to reuses a single instance. As with all Flex development, the Flex Profiler should be used to ensure popup views are successfully garbage collected, since they can be a source of memory leaks.</p>

<p>Here is another example where the popup view is declared as an in-line component, in a similar manner to an item renderer on a list-based control.</p>

<pre>
&lt;popup:PopUpFactory 
    open="{model.openPopUp}"
    reuse="false"&gt;
    &lt;mx:Component&gt;
        &lt;mypopup:MyPopupView
            title="{outerDocument.model.popUpTitle}"/&gt;
    &lt;/mx:Component&gt;
&lt;/popup:PopUpFactory&gt;
</pre>

<p>The <tt>PopUpFactory</tt> tag also provides the same properties as the <tt>PopUpWrapper</tt> tag, since they both inherit from a common base class.</p>

<h2>Popup Behaviors</h2>

<p>When we first introduced a declarative approach for popups to our projects, we noticed developers customizing the classes with more and more specific behavior. In one situation, a popup needed to play a transition while opening; in another the popup had to remain centered whenever its contents resized. Soon the popup tags became bloated with code for handling all of these special requirements, each applicable only to one or two popups. </p>

<p>The <tt>IPopUpBehavior</tt> interface was introduced to extract these specialities into their own classes. In this way, a set of behaviors can be created, independent of one another, and the appropriate behaviors can be applied for a given situation. This design creates a nice extensibility point, allowing developers to write their own behaviors without needing to customize the declarative tags at all.</p>

<p>Here is an example of a popup with a number of behaviors applied.</p>

<pre>
&lt;popup:PopUpFactory
    open="{model.showPopUp}"
    factory="my.package.MyPopUpView"&gt;
    &lt;popup:behaviors&gt;
        &lt;mx:Array&gt;
            &lt;popup:ZoomAndFadePopUpBehavior/&gt;
            &lt;popup:KeepCenteredPopUpBehavior/&gt;
        &lt;/mx:Array&gt;
    &lt;popup:behaviors&gt;
&lt;/popup:PopUpFactory&gt;
</pre>

<p>In this case, two custom popup behaviors are being applied. The first plays a zoom and fade effect upon opening and closure, while the second ensures that the popup remains centered whenever its contents is resized. The declarative approach makes it simple to configure these behaviors.</p>

<p>To write your own popup behavior, just implement the <tt>IPopUpBehavior</tt> interface:</p>

<pre>
public interface IPopUpBehavior
{
    function apply(opener:PopUpBase):void;
}
</pre>

<p>A reference to the popup component is passed through the <tt>apply()</tt> method to each behavior. The behavior can then attach event handlers in order to control the behavior of the actual popup while it is opened or closed. Some examples are provided in the sample project (download above). A behavior can also suspend and resume closure by calling the <tt>suspendClosure()</tt> and <tt>resumeClosure()</tt> methods of the <tt>PopUpEvent</tt> class. This allows something asynchronous, such as the playing of an effect, to take place during closure, before the popup is actually removed from the display list.</p>

<h2>How Does It Work?</h2>

<p>The design for the popup tags is relatively simple. There's a common base class -- <tt>PopUpBase</tt> -- that is extended by the two tags: <tt>PopUpWrapper</tt> and <tt>PopUpFactory</tt>. The base class contains the common properties -- <tt>open</tt>, <tt>center</tt>, <tt>modal</tt> -- and also holds an array of behaviors, applying them during opening and closure. The two concrete tags implement different creation and destruction policies using the standard mechanisms for deferred instantiation and object factories: <tt>IDeferredInstance</tt> and <tt>IFactory</tt>. The Flex compiler takes care of the rest, converting the declared popup view into an appropriately configured <tt>DeferredInstanceFromFunction/Class</tt> or <tt>ClassFactory</tt> object. See the Flex Language Reference for more details.</p>

<h2>Conclusion</h2>

<p>We've been using versions of these tags on our projects for several years now. They help us to separate concerns, keeping our views as simple declarations of components, free from script block logic that would make them harder to understand and more difficult to unit test.</p>

<p>It's worth noting that Flex 4 includes its own declarative tag -- <tt>PopUpAnchor</tt> -- which also takes advantage of MXML and deferred creation, but it is designed for drop-down menu scenarios. There are some similarities, but the <tt>PopUpWrapper</tt> and <tt>PopUpFactory</tt> components are designed for more general popup handling. Perhaps a future version of the SDK will include declarative tags that make it simple to manage the life-cycle of popups and apply different behaviors, but in the meantime we hope you enjoy using these components.</p>
]]>
    </content>
</entry>

<entry>
    <title>The Trend Towards Inversion-of-Control Frameworks in Flex</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2009/07/the_trend_towards_inversionofc.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=11301" title="The Trend Towards Inversion-of-Control Frameworks in Flex" />
    <id>tag:blogs.adobe.com,2009:/tomsugden//142.11301</id>
    
    <published>2009-07-06T07:35:31Z</published>
    <updated>2009-07-19T21:33:09Z</updated>
    
    <summary>Last year I wrote three chapters about the Cairngorm MVC framework for a new Flex book, Professional Flex 3, published by Wrox Press. Cairngorm has been widely adopted on enterprise projects, so it was important to explain its workings and...</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Frameworks" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>Last year I wrote three chapters about the Cairngorm MVC framework for a new Flex book, <a href="http://www.amazon.com/Professional-Adobe-Flex-Wrox-Programmer/dp/0470223642/ref=sr_1_1?ie=UTF8&s=books&qid=1246894407&sr=8-1">Professional Flex 3</a>, published by Wrox Press. Cairngorm has been widely adopted on enterprise projects, so it was important to explain its workings and cover the best practices and common pitfalls. If you’re a developer who moves between clients and projects, this is important knowledge to have. However, with more time and pages, I’d have liked to devote similar attention to the other Flex frameworks now available.</p>

<p>Over the last few years, the Flex framework space has become well served with alternatives to Cairngorm, each offering their own take on the challenges of RIA development. While Cairngorm is rooted in design patterns from the Java enterprise world, some of the newer framework creators have taken a fresh approach, reflecting on the language features and special capabilities of ActionScript and the Flex SDK, then building from the ground up, taking advantage of features like event bubbling, declarative MXML and metadata.</p>]]>
        <![CDATA[<p><strong>Inversion-of-Control</strong></p>

<p>In these new frameworks, there has been a trend towards the <a href="http://martinfowler.com/articles/injection.html">inversion-of-control (IoC) or dependency-injection</a> pattern. There is a good reason for this, since this approach decouples the objects of an application, so they can change independently of one another and be tested in isolation. Applying IoC can make it easier to restructure a user interface, substitute the service integration layer, and refactor the models containing the logic and state of your application, amongst other benefits.</p>

<p>For those new to the concept, IoC means passing (or injecting) the dependencies for a class into that class, instead of creating the dependent objects within. The behavior of a class can then be controlled by passing in different types of objects; an inversion of the traditional approach. When interfaces are extracted from these dependencies, the technique becomes more powerful, because the class is decoupled from any concrete classes. The interfaces can be implemented in different ways to achieve different outcomes and can be substituted for testing purposes. </p>

<p>An example of this design is found in the <tt>Tree</tt> component of the Flex SDK. The Tree uses the <a href="http://livedocs.adobe.com/flex/3/langref/mx/controls/treeClasses/ITreeDataDescriptor.html"><tt>ITreeDataDescriptor</tt></a> interface to determine whether the items in its data provider are branch or leaf nodes. </p>

<pre>
public interface ITreeDataDescriptor
{
    ...
    isBranch(node:Object, model:Object = null):Boolean
    ...
}
</pre>

<p>This interface decouples the <tt>Tree</tt> from the actual type of objects inside the data provider. By substituting different implementations of <tt>ITreeDataDescriptor</tt>, it can be made to render all kinds of objects in tree form. This inversion of control makes the <tt>Tree</tt> a more flexible component than it would be if a single data descriptor of fixed type was created internally.</p>

<p><strong>Inversion-of-Control Frameworks in Flex</strong></p>

<p>A number of IoC-based frameworks have emerged for Flex to support the development of loosely-coupled applications. They typically provide a way to configure the main objects used by the application (models, services, etc.) and to specify the dependencies between them. These frameworks are sometimes known as IoC <em>containers</em>, where the container is the part of the framework responsible for instantiating objects and setting-up (or <em>wiring</em>) the dependencies. In some cases, the container assumes further responsibilities, such as managing the life-cycle of the objects (calling initialization and disposal methods) or routing messages from one object to another.</p>

<p>To give a potted history, two of the earlier arrivals were <a href="http://www.pranaframework.org/">Prana</a> and <a href="http://www.spicefactory.org/parsley/">Parsley</a>, both of which were inspired by the popular Spring framework from the Java world. They used XML files for configuration and singletons for extracting pre-configured objects from the containers into Flex views. The generation that followed, including <a href="http://code.google.com/p/swizframework">Swiz</a> and the lesser-known <a href="http://sourceforge.net/projects/flicc">Flicc</a>, were lighter weight and took more advantage of features of Flex. Swiz took the most radically simple approach, defining objects (or <em>beans</em>) directly in MXML and injecting them automatically into views wherever a special metadata tag was placed, while Flicc provided a novel set of MXML tags for object definition, event handling and view injection.</p>

<p>Since then all of these frameworks have been evolving. Prana has become Spring ActionScript, an extension of the official Spring Platform, while Parsley picked up some tricks from Swiz and Flicc and broadened its feature set to include messaging, module integration and extensibility points. Swiz too has gained new capabilities while remaining distinctly lightweight, like prototype object instantiation (a.k.a. non-singletons) and more flexible event mediation with bubbling events and metadata. A more detailed comparison of these frameworks together with sample applications is due to be published soon on Adobe Devnet in an article written by my colleague, Ed Eustace (link will be added after publication).</p>

<p><strong>Conclusion</strong></p>

<p>The frameworks space is in good shape for Flex. Established MVC frameworks like Cairngorm and Pure MVC, that prescribe certain design patterns and structures, have been complemented by a slew of new frameworks<sup>1</sup> centered around inversion-of-control. When applied correctly, these enable developers to write more loosely-coupled software that can be changed and tested more easily.</p>

<p>However, inversion-of-control is a very general approach that can be applied in different ways. Questions remain about the best way to use it for building Flex applications. For advanced developers, the freedom afforded by these new frameworks is a benefit, since their experience enables them to make wise judgements about how to structure the layers of an application (view, model, control, integration, etc). For less experienced developers, however, the pattern alone provides little guidance and mistakes can easily be made. Since software project teams tend to consist of multiple developers with different levels of experience, it is important to establish guidelines around the use of an IoC framework for a team to deliver efficiently.</p>

<p>The variety of approaches and competition between frameworks is in the interests of Flex developers and end users. It’s giving us better solutions to the recurring problems of RIA development, allowing us to focus on what is special and distinct about our projects, rather than the basic plumbing. There are some opportunities for consolidation and there's no one-size-fits-all solution at present, so technical architects need to evaluate carefully and choose the best framework for a particular situation, given the technical considerations and also the makeup of the team. </p>

<p>Progress looks to be steady with the current selection of frameworks, but perhaps new capabilities are needed for Flash Player and the Flex SDK to enable the next major leap forward?</p>

<p><sup>1</sup> The Mate Flex Framework and probably others have been unfairly overlooked in this blog post. Although not positioned as an inversion-of-control container, Mate does provide a means of dependency injection together with a neat set of declarative MXML tags to structure and coordinate a Flex application.</p>

<p><strong>Coming Up</strong></p>

<p>In a future post, I’ll write in more detail about Parsley 2, the second version of the Parsley Application Framework. Parsley has arguably the richest feature set of the current generation of frameworks, yet it also has a simple elegance. The blog post will focus on two of the features that currently distinguish it: module integration and loosely-coupled messaging.</p>]]>
    </content>
</entry>

<entry>
    <title>EventfulTestCase: a FlexUnit extension for testing event dispatching</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/tomsugden/2008/01/eventfultestcase_a_flexunit_ex.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=142/entry_id=4863" title="EventfulTestCase: a FlexUnit extension for testing event dispatching" />
    <id>tag:blogs.adobe.com,2008:/tomsugden//142.4863</id>
    
    <published>2008-01-11T22:28:02Z</published>
    <updated>2009-08-11T08:49:50Z</updated>
    
    <summary>The events that a class dispatches form an important part of its contract with clients, yet for one reason or another they are seldom tested. Perhaps this is because event declarations are optional in Flex and specified as metadata, or perhaps it is because the FlexUnit assertions were mostly ported from JUnit and not tailored specifically to Flex. In either case, programming mistakes and design flaws in event logic can have far-reaching consequences, effecting any dependent event listeners and the classes beyond them.
</summary>
    <author>
        <name>Tom Sugden</name>
        
    </author>
    
        <category term="Cairngorm" />
    
        <category term="FlexUnit" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/tomsugden/">
        <![CDATA[<p>
<b>
NOTE: The extension described in this post has now been incorporated into FlexUnit 3. The syntax has changed slightly, but the concepts described in this post remain. This feature is not yet available in FlexUnit 4, which is a major update, but work is underway to provide even better support for unit testing the event dispatching behavior of your classes.
</b> 
</p>

<h3>Introduction</h3>

The events that a class dispatches form an important part of its contract with clients, yet for one reason or another they are seldom tested. Perhaps this is because event declarations are optional in Flex and specified as metadata, or perhaps it is because the FlexUnit assertions were mostly ported from JUnit and not tailored specifically to Flex. In either case, programming mistakes and design flaws in event logic can have far-reaching consequences, effecting any dependent event listeners and the classes beyond them.
]]>
        <![CDATA[<p>
To illustrate the importance of event testing, consider the case of a NuclearReactor class that dispatches <em>temperatureChange</em> events to indicate the effect of adding fuel. Perhaps we also have a MeltdownAlert class that listens for these events in order to raise an alert whenever a boundary temperature is crossed. The melodrama should make it obvious: if the NuclearReactor has a bug that prevents it dispatching events in the expected manner, the MeltdownAlert will never trigger and a catastrophe will unfold.
</p>

<p>
So it is clearly important to ensure event dispatching logic is correct. To promote the best-practice of unit testing the dispatch of events, I have written a small extension to the FlexUnit TestCase class that makes it easy: <em>EventfulTestCase</em>. This is a new base class for any tests that involve the dispatch of events. It supports both standard Flash events and also Cairngorm events. 
</p>

<p>
The following ActionScript source files accompany this post:
</p>

<ul>
<li><a href="http://blogs.adobe.com/tomsugden/eventful/EventfulTestCase.as">EventfulTestCase.as</a> - the FlexUnit TestCase extension.</li>
<li><a href="http://blogs.adobe.com/tomsugden/eventful/EventListener.as">EventListener.as</a> - a helper class required by EventfulTestCase.as</li>
<li><a href="http://blogs.adobe.com/tomsugden/eventful2/CairngormEventSource.as">CairngormEventSource.as</a> - optional class only needed for testing Cairngorm event dispatching</li>
</ul>

<h3>Writing Eventful Test Cases</h3>

<p>
The process of writing an eventful test case involves first recording the expected events, then performing the action under test, and finally asserting that the expected events occurred. EventfulTestCase defines three kinds of functions to help with this:
</p>

<ol>
<li><em>expect functions</em> - used to record the events that are expected to occur during the test case.</li>
<li><em>assert functions</em> - used to assert that the expected events actually occurred.</li>
<li><em>actual event getters</em> - used to access the actual events that were heard so that more specific assertions can be carried out.</li>
</ol>

<p><b>Example 1: testing the dispatch of normal events</b></p>

<p>
Shown below is a simple example which asserts that the <em>temperatureChanges</em> event is dispatched when the addPlutonium() function is called.
</p>

<pre>
public function testAddPlutonium() : void
{
   // record the expected event
   expectEvent( reactor, TemperatureChangeEvent.TEMPERATURE_CHANGE );
         
   // perform the action that is being tested
   reactor.addPlutonium( plutonium );
         
   // assert that the expected events occurred
   assertExpectedEventsOccurred( 
      "The temperature change event was not dispatched." );
}
</pre>

<p>
If the expected event is not dispatched, the test case will fail and the developer will be presented with a failure message to assist in debugging. In this case, the message might look like: <em>"The temperature change event was not dispatched. Expected events &lt;temperatureChangedEvent&gt; but heard events &lt;reactorStoppedEvent&gt;"</em>. Now the developer knows that the addPlutonium() function contains a logical error which causes the wrong event to be dispatched.
</p>

<p><b>Example 2: testing the dispatch of Cairngorm events</p></b>

<p>
The next example is a little more complex and asserts that two Cairngorm events have occurred. Since Cairngorm events are dispatched through the CairngormEventDispatcher singleton instead of a regular Flex EventDispatcher, the<em> CairngormEventSource</em> adapter class must be used as the event source.
</p>

<pre>
public function testRefreshPlutoniumStocks() : void
{
   // record the expected events
   expectEvents( 
      CairngormEventSource.instance, // adapter for Cairngorm events
      GetLocalPlutoniumStocksEvent.EVENT_NAME,
      GetNationalPlutoniumStocksEvent.EVENT_NAME );
    
   // perform the action that is being tested
   reactor.refreshPlutoniumStocks();
 
   // assert that the expected events occurred
   assertExpectedEventsOccurred(
      "The Cairngorm events to fetch local and national " +
      "plutonium stocks were not dispatched." );
}
</pre>

<p><b>Example 3: performing more detailed assertions</p></b>

<p>
The final example builds on the first, demonstrating how to use the actual event getters for performing more detailed assertions.
</p>

<p>
<pre>
public function testAddPlutonium() : void
{
   // record the expected event
   expectEvent( reactor, TemperatureChangeEvent.TEMPERATURE_CHANGE );
         
   // perform the action that is being tested
   reactor.addPlutonium( plutonium );
         
   // assert that the expected events occurred
   assertExpectedEventsOccurred( 
      "The temperature change event was not dispatched." );

   // assert on the details of the actual event
   var temperatureChangeEvent : TemperatureChangeEvent = 
      TemperatureChangeEvent( lastActualEvent );
      
   var expectedTemperature : Number = 550;
      
   assertEquals(
      "The expected temperature change did not occur.",
      expectedTemperature,
      temperatureChangeEvent.temperature );
}
</pre>
</p>

<h3>Known Limitations</h3>

<p>
EventfulTestCase only listens for the expected events and cannot hear unexpected events. The consequence of this is limited detail in the test failure messages. Only the expected events that actually occurred can be reported. The reason for this limitation is that the Flex framework does not enable us to listen to unspecified event types. In other words, we need to register listeners explicitly for each type of event that we want to listen to. One work-around would be to override the dispatchEvent() function of the EventListener framework class, but that would be overly intrusive. This limitation is not severe since the failure messages that can be provided are still reasonably useful.
</p>

<p>
It should also be noted that EventfulTestCase relies on the fact that most event dispatching takes place synchronously in Flex. When a function dispatches an event, we can be sure that any registered listeners will hear that event synchronously before the function continues and returns. In Flex applications, asynchronicity is typically confined to the I/O operations performed by the Flash Player, and these sit outside the normal realm of unit testing. It is usually possible to mock genuinely asynchronous behaviour, so that the class in question can be tested synchronously. When this is not the case, or for integration testing purposes, a more sophisticated solution is required.
</p>

<h3>Conclusion</h3>

<p>
The bugs and design flaws associated with event dispatching often slip the net when unit testing, allowing them to lurk in the deep and strike later. The EventfulTestCase extension helps to prevent this by making it quick and easy to test event dispatching. The process involves three stages: recording expectations, performing actions and asserting that the events occurred. As we attempt to build bigger and better Flex applications, we must test more thoroughly to ensure our success, and this must include testing events.
</p>]]>
    </content>
</entry>

</feed> 

