samples

Using the Abstract Factory pattern with Flex

Accordingly to the Gang of four the Abstract Factory pattern intent is to provide an interface for creating families of related or dependent objects without specifying their concrete classes.
This design pattern actually ensures that the patterns automatically get and use the correct object accordingly to the context in which the client is working.
There are many different situations in which this pattern can work, imagine for instance a system in which the drawing and printing method varies accordingly to the resolution supported by the system; the system has to use different drivers in different cases.
At a first glance you may be tempted to use two different switch case for the drawing and printing procedure in which your system reacts in a different way accordingly to the resolution but remember that switches may indicate the need of abstraction in your system and that it can bring your system to a combinatorial explosion (imagine to add new drivers for each different resolution and create and even more complex switch case).
A good way to solve this issue us to create a Factory that creates the appropriate object accordingly to the resolution supported by the system, in this way you avoid the combinatorial explosion I mentioned and you can keep the switches in a single place or even better accordingly to the language you are working on and to your code style you can avoid switches also in the factory.
We have talked since now about two possible families of objects to use, monitor and printer drivers. Give me a chance to introduce you to a more complex system, an e-commerce with a group of families related to the system payments

•    Credit Card
•    OnLine payment
•    Other payment

For each of these families you may have the need to define multiple objects when you system starts

•    Credit Card
o    Visa
o    American Express
o    Master Card
•    OnLine payment
o    Paypal
o    E-check
•    Other payment
o    Wire transfer
o    Check

and add even more objects when the system grows or when new payment methods will be released over the net.
In an e-commerce system you may also have the need to show to the user the appropriate payment system accordingly to his preferences, in order to increase the abstraction of your system you can define multiple Abstract classes and keep the system ignorant on which particular implementation is in use because the factories are the responsible to instantiate them.
Imagine the scenario I described an put it in an UML diagram

Abstract Factory

The application is composed by a form that contains a submit button and the form fields vary accordingly to the user preferences retrieved by the system.
The CheckOutFactory class is an abstract class that have two concrete implementations able to return to the client the UI needed for each payment (actually the MXML representation of the class). The PaymentContainer is a VBox with a property used to store a reference to the payment form created from the factory that implements an interface that defines two common methods of the payment forms

•    validateFields()
•    submit()

As you know ActionScript 3.0 doesn’t support abstract classes, so the CheckOutFactory simulates the abstraction of the class trough the use of an internal class in its constructor.
Another good way to implement the abstraction is the use of interfaces, this is the reason why I defined a common interface ICheckOut and two other interfaces (IOnlinePayment and ICreditCard) that extend the base interface and that will be implemented in the view of each payment form of the system.
Take a look to the class hierarchy in order to understand where we are and where we are going

class hierarchy

The abstraction of the on-line and credit card payments is reached through the interfaces put on the top of the onLinePayment and creditCardPayment packaging, the view and it’s logic has been keep separated through the Model View Presenter pattern used from each payment form.
Each presenter implements a public submit() method, in this way you can call in a centralized fashioned way the submit of each form trough the PaymentContainer property named element, each presenter will have the responsibility to recover the data from the view and each view, due to the fact that implements the ICheckOut interface, validate it’s fields (a good idea is to validate each credit card with a different Validator, this is the reason why you find an instance of the CreditCardValidator class in the  credit card payment forms.
In order to run this sample (view source enabled) I created an XML file that stores the name of some users and the payment preferences, each node has the following structure

<user name = "Giorgio Natili" mode = "OnlinePayment" type = "PayPal" />

In the main application a combo box is populated with this data and each time you change the selection a concrete factory is created and through the factory a new view is added to the PaymentContainer

private function onUserSelection(e:Event):void{
checkOutFactory = CheckOutFactory.getPaymentFacotry(e.target.selectedItem.@mode);
var s:String = e.target.selectedItem.@type;
checkOutModule = checkOutFactory.getUI(s.substr(0, 1).toLocaleLowerCase() + s.substring(1, s.length) + ".view." + s + "View");
paymentContainer.element = checkOutModule;
}

The checkOutFactory and the checkOutMopdule properties data type represents the layer of abstraction I’m searching for
private var checkOutFactory:CheckOutFactory;
private var checkOutModule:ICheckOut;
The method defined as a listener for the click event inside the PaymentContainer uses the methods defined in the ICheckOut interface to complete his task

private function doSubmit():void{
if(_element.validateData()){
_element.submit();
}else{
Alert.show("Invalid data in the form...", "Attention!");
}
}

At the end of the day we have a quite flexible sample, but which are the benefits of this pattern? It would be simpler to have a switch instead of all this code?
The main benefit is that if you have to add the support for another credit card you have to deal only with the logic stored in the MVP triad you need to add a payment form and the system automatically will be able to handle the new form.
The switch could be hard to maintain in a situation with more than 4 payment methods, moreover the abstraction layer that the system has reached give to you the flexibility to put each developer you want on the new payment forms the system needs without having to explain to the developer anything about the system itself.

There are other possible contexts in which the Abstract Factory pattern can be used

•    Handle different operating systems API in a cross platform application
•    Different traits for users of an application
•    Different version of an application
•    Different performance guidelines

At the end of the day we can recap with the following points the Abstract Factory pattern

•    You want to have families or sets of objects for particular clients
•    Families of related objects have to be instantiated
•    You want to coordinate the creation of families of objects
•    You need to isolates the rules of which objects are to be made

Obviously this is only a small sample and more complex implementation are out of the scope of this blog entry, so feel free to open a discussion on this topic.

Flex item renderers, an expandable list with transitions

I think that each flex developer at a certain point have had the necessity to work with custom item renderers in order to display data in a fancy way.
There is a lot of knowledge around the web regarding this topic but I want to show the process that has driven me to a list that contains custom item renderers with different states and with transitions between each state.
In order to perform this task I’ll show to you how you can create a simple item render, an item renderer with two different states, an item render with some transitions with a visual bug (it’s the default rendering of the list) and one without any bug.
I know that an expandable list can be done also with a VBox and Repeater and that it perform nicely but the list has a caching procedure of the item renderers that is very useful when you have to render on the screen a great number of complex renderers.

A simple item render
Imagine the simple scenario in which your layout require something more than a label in a list and you need to add for instance a “buy now” button, you can create an MXML component

<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
verticalScrollPolicy="off" horizontalScrollPolicy="off"
paddingBottom="5" paddingLeft="5" paddingRight="5" paddingTop="5">
<mx:Button label=" Buy now " enabled="false"/>
<mx:Label text="{data.name}"/>
</mx:HBox>
and set it as the item renderer in the List control
<mx:List id="list" height="300" dataProvider="{listData}" itemRenderer="SimpleRenderer" />

The dataprovider is an ArrayCollection that contain several Article value objects, the class that define an article can be summarized with the following UML diagram

A multi state item render
Imagine now the scenario in which an item renderer needs to show some data and expand itself in order to display on the screen more information about this item, first of all create an MXML component that extends the VBox and that contain three different states, in the first one the component have to show the article name and a button to expand the content

in the second state the component needs to render the price of the article, a “buy now” button and a control in order to expand the third state

In the third state the component has to render the details of the article

In order to complete this task you can define the UI of the component with the following MXML using the <mx:states> tag to define states, label and event handler

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:HBox>
<mx:Button label="Expand" id="_expand" click="currentState='opened'"/>
<mx:Label text="{this.name}"/>
</mx:HBox>
<mx:states>
<mx:State name="opened" >
<mx:SetProperty target="{_expand}" name="label" value="Collapse"/>
<mx:AddChild position="lastChild">
<mx:HBox id="_dataRender"  width="100%" verticalAlign="middle" >
<mx:Label id="_article"  text="Article" width="80"/>
<mx:Label id="_price" text="Price" width="80"/>
<mx:Button label="Order"/>
<mx:Spacer width="100%"/>
<mx:Button label="Show Details" id="_details" click="currentState='details'"/>
</mx:HBox>
</mx:AddChild>
<mx:SetEventHandler target="{_expand}" name="click" handler="currentState=''"/>
</mx:State>
<mx:State name="details" basedOn="opened">
<mx:AddChild position="lastChild">
<mx:Text id="_detailsData" text="Description" width="100%" height="60" />
</mx:AddChild>
<mx:SetProperty target="{_details}" name="label" value="Hide Details"/>
<mx:SetEventHandler target="{_details}" name="click" handler="currentState='opened'"/>
</mx:State>
</mx:states>
</mx:VBox>

If you come back to the list and set this component as an item renderer you will see that the nested states are not rendered, you have to define the List as a variable row list

<mx:List id="list" height="300" dataProvider="{listData}" itemRenderer="SimpleRendererStates"  variableRowHeight = "true" />

Now the list is able to render the nested states but if you scroll up and down the list you will see that the states and the data of each item renderer are not consistent with your model, this is due to the List behavior that recycle components in order to render data, when items scroll out of view, its itemRenderer will be moved to the bottom of the list.
In order to keep state and data consistent you have to perform some changes in your code, first of all my suggestion is to create a class that can hold state information and data of each item (in this way also if you work with remote value object you don’t need to make any change on the server side), the class can be summarized with the following UML diagram

the state property contains a string that represent the currentState of the component, the renderData property represents the data you need to display in the components.
Inside your component override the public data method in order to be sure that each time the data changes (each time the list is scrolled) the UI elements are updated

override public function set data(value:Object):void{
super.data = value;
if(!data)return
var dt:Article = data.renderData;
if(_article)_article.text = dt.name;
if(_price)_price.text = String(dt.price);
if(_detailsData)_detailsData.text = dt.description;
invalidateProperties();
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}

Please not that in the method the article value object has been extracted from the object used to define the data of each item.
In order to keep track of the state of each item render override the currentState method and store the value of the new state in the model

override public function set currentState(value:String):void{
super.currentState = value;
if(data)data.state = value;
}

Now is the time to handle the state value in the commitProperties protected method

override protected function commitProperties():void{
super.commitProperties();
if(!data)return;
currentState = data.state;
}

The List component needs to know the dimension of the item render in order to gracefully adapt each item to its state, this is the reason why in the measure() method you have to explicitly set the values of the properties measuredHeight and measuredMinHeight for each state

override protected function measure():void{
super.measure();
if(!data)return;
switch(true){
case currentState == "":
measuredHeight = 30;
measuredMinHeight = 30;
break;
case currentState == "opened":
measuredHeight = 70;
measuredMinHeight = 70;
break;
case currentState == "details":
measuredHeight = 110;
measuredMinHeight = 110;
break;
}
}

If you compile your application now the item renders display the data and the states in a consistent way.

A multi state item render with transitions
In order to add a transition between each state of the your item renderer add the following MXML tags to the previous component and save it with a different name

<mx:transitions>
<mx:Transition fromState="*" toState="*">
<mx:Resize target="{this}" />
</mx:Transition>
</mx:transitions>

If you try now the list with this item renderer you’ll be surprised, the transitions don’t perform very well because the item renderer doesn’t know anything about the state in the data method so use an event handler for the StateChangeEvent.CURRENT_STATE_CHANGE event

protected function onStateChange(e:StateChangeEvent):void{
if(!data)return
var dt:Article = data.renderData;
if(e.newState == ""){
dt.opened = 0;
}
if(e.newState == "opened"){
dt.opened = 1;
}
if(e.newState == "details"){
dt.opened = 2;
}
}

and store a specific int value in the opened property of each value object.
In the overridden data method add a switch case to handle this value

switch(true){
case dt.opened == 0:
currentState = "";
break;
case dt.opened == 1:
currentState = "opened";
break;
case dt.opened == 2:
currentState = "details";
break;
}

Now your item renderer is able to handle state and transitions but you’ll see that scrolling the List when it has to render again an item each transition is rendered with a delay, this is due to the live cycle of the List that calls a last udpateDisplayList after a while, in order to solve this stuff you have to put your hands inside the List source code and create an easy reusable class for the item render.

A smart multi state item render with transitions
Surfing the web I found a nice article on item renderers but when I read this sentence “I think a resizing itemRenderer is too complex and not really worth the effort. I believe there is a better way to do this using VBox and Repeater. However, the catch with Repeater is that every child will be created. If you have 1000 records and use a Repeater, you will get 1000 instances of your itemRenderer.” my mind started to think to a solution because with a great number of instances of a complex item renderer the performance of each Flex application can be seriously impacted.
I started to read the source code of the List and I found the two methods that recycle or create the item renderers in the list

getReservedOrFreeItemRenderer(data:Object):IListItemRenderer
createItemRenderer(data:Object):IListItemRenderer

In order to avoid the delay I need to change the state of each item renderer in these two methods, the first issues I found are that the transitions defined in the item renderer stop to work and that the height is not rendered.
The other issue I found is that without a base class each time I would like to use smart item renderers in my List I have to start over.
The solution I found is create a VariableRowList  class that extends the List, define a base class for item renderers (I started with a class for VBox based item renderers), define an interface that define a method to use in order to update the state and the height and define the effects I need outside the <mx:tranisitions> tag.
The VariableRowList  class makes an override of the methods used in order to create and recycle the item renderers and attempt to call the method defined in the interface ISmartRenderer the renderer needs in order to handle its state and its height at the end of each method

try{
ISmartRenderer(item).updateState(dt.state);
}catch(e:Error){
trace("It's not an ISmartRenderer implementors")
}

The ExpandableVBoxRenderer class first of all implements two interfaces, IDropInListItemRenderer and ISmartRenderer, and define a constant that hold an array of objects used to define the heights for each state

protected const STATES_HEIGHT:Array = [{state: "", height: 30}, {state: "opened", height: 60}, {state: "details", height: 110}];

In the constructor of this class you find the definition of a listener for the StateChangeEvent.CURRENT_STATE_CHANGE  and for the FlexEvent.CREATION_COMPLETE events and the policy for the scroll bars

this.addEventListener(StateChangeEvent.CURRENT_STATE_CHANGE, onStateChange);
this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
this.verticalScrollPolicy = ScrollPolicy.OFF;
this.horizontalScrollPolicy = ScrollPolicy.OFF;

The override of the data method use a protected method populateControl() that use the data stored in the  renderData property of the SmartRenderData class in order to populate the UI elements (this method is empty and need to be overridden from the classes that extend the ExpandableVBoxRenderer)

override public function set data(value:Object):void{
super.data = value;
if(!data)return;
data.state = currentState;
populateControl(data.renderData);
invalidateProperties();
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}

In the override of the measure method the class calculates the needed height trough a private method that get the data from the STATES_HEIGHT constant

override protected function measure():void{
super.measure();
if(!data)return;
var currentHeight:Number = recoverHeight(currentState || "");
measuredHeight = currentHeight;
measuredMinHeight = currentHeight;
}

The updateState method defined in the ISmartRenderer interface update the state and the height of the component and call the measure method

public function updateState(state:String):void{
currentState = state;
height = recoverHeight(state);
measure();
}

If you want now start to use this stuffs define the namespace you need to use the VariableRowList   class in your application and place these tags in place of the List you have used before

<gn:VariableRowList dataProvider="{listData}" itemRenderer="it.mxml.expandableList.view.ExtendedRenderer" />

Define now a new class that extends the ExpandableVBoxRenderer and use it as the base class for a new MXML component that will have the same tags of the one you defined in order to handle the transitions except for the transitions that will be removed and that will be substituted from the following effects

<mx:Resize id="openInfo" duration="205" heightFrom="30" heightTo="60" target="{this}" />
<mx:Resize id="openDetails" duration="205" heightFrom="60" heightTo="110" target="{this}" />

Came back in the class and define the public members that point to the controls defined via MXML

[Bindable]public var _article:Label;
[Bindable]public var _price:Label;
[Bindable]public var _detailsData:Text;
[Bindable]public var _details:Button;
[Bindable]public var _expand:Button;

Override the populateControls() method in order to render the data inside the item renderer

override protected function populateControl(data:Object):void{
if(_article)_article.text = data.name;
if(_price)_price.text = data.price;
if(_detailsData)_detailsData.text = data.description;
}

and define the handlers for the click event on the buttons in order to play the effect defined trough MXML (see in the source of the sample application to check the other handlers)

private function onDetails(e:MouseEvent):void{
if(e.target.label == "Show Details"){
currentState = "details";
this["openDetails"].play()
}else{
currentState = "opened";
this["openDetails"].play(null, true)
}
}

In this way your List will be able to render the data and the transition like a charm, check the sample application and the source code (right click, view source) in order to read the complete implementation.

Resources
http://www.returnundefined.com/2006/10/item-renderers-in-datagrids-a-primer-for-predictable-behavior

http://blogs.adobe.com/aharui/item_renderers/

http://flexdiary.blogspot.com/2007/11/order-of-events-for-itemrenderers.html

http://www.adobe.com/devnet/flex/articles/itemrenderers_pt4_print.html

Introduction to MVP for Flex

In these days I spent a lot of time to get a deeper knowledge about the Model View Presenter design pattern and at the end of the day I have to say “it rocks!”.
The Model View Presenter design pattern is a variation of the Model View Control that in a similar way separate the concerns of an application’s data, presentation and user input into specialized components.
The original implementation of the MVP is born in the 1979, its name was Thing Model View Editor and during these years there were a lot of different implementations between them the Taligent’s one (1996) was for sure the more sophisticated and the more powerful.

During the preparation of material on presentation layer patterns in 2006 Martin Fowler decided that the treatment given to the MVP pattern must be divided under the names Supervising Controller and Passive View.
In the first one the View delegate user events to the Controller which in turn interacts with the business logic of the application and the uses data binding techniques and the Observer Pattern to update itself when changes occur in the model.

Supervising Controller decomposes presentation functionality into two parts: a controller (often called presenter) and view. The domain data that needs to be displayed is separate, and following rough MVC terminology I’ll refer to it as a model, although it need not be a Domain Model.
In the second one the Controller is always the one that handle user input and that interact with the business logic but it’s also the responsible of the update of the view. In this way the view maintain no links with the Model and relies only on the controller for the all the presentation logic.
This pattern is yet another variation on model-view-controller and model-view-presenter. As with these the UI is split between a view that handles display and a controller that responds to user gestures. The significant change with Passive View is that the view is made completely passive and is no longer responsible for updating itself from the model. As a result, there is no dependencies in either direction between the view and the model.

These patterns are anther evolution of the MV* family, but came back again to the MVP and let’s try to see the building blocks of its implementation (I really want to point your attention on the building blocks words because in the future I want to show a Taligent like implementation of MVP in Flex) and on the wiring between the presenter and view.
In the sample implementation we’ll discover in this post we’ll take in exam a simple form used to recover the details of some customers stored in a simple XML file.
The View is responsible for visual representation of the UI and it contains a presenter in private field. View is implementing interface whose members are approximated and technology striped UI elements of the view. When some event occurs on view is just forwarding it to presenter and it is presenter responsibility to handle the event. Presenter is manipulating view by talking to interface representation of the view. Presenter should never reference directly view members (UI controls). Presenter for his logic operations is using Model which can be persisted state or representation of the object which provides necessary functionality.

In the application sample you find here there are a lot of actors: an MXML file that contains an instance of the UserView component that extends tha VBox class, the IUserView interface that defines the method the view needs to update its state, the UserViewPresenter class that is the responsible of the search operation and of the update of the view

The MXML fine that holds the application is self explanatory, it only defines the custom component view

<contactDetail:UserView x="10" y="10" />

The interface IUserView (implemented by the UserView.mxml file) define the methods we need in order to update the view and get the search criteria from the view to complete the operation

function set userName(value:String):void;
function set lastName(value:String):void;
function set city(value:String):void;
function set errorMessage(value:String):void;
function get searchCriteria():String;

The UserView custom component contains the MXML tag needed to define the UI (sorry for not using code behind but the focus of the post is different) and the call to the recoverData() method defined in the presenter

<mx:Label text="Contact Details Manager" width="100%" fontWeight="bold"/>
<mx:Label id="_errorMessage"  width="100%" color="#FF0006"/>
<mx:Form width="100%" height="50%">
<mx:FormItem label="Name" width="100%">
<mx:TextInput id="_userName" editable="false" width="100%"/>
</mx:FormItem>
<mx:FormItem label="Surname" width="100%">
<mx:TextInput id="_lastName" editable="false" width="100%"/>
</mx:FormItem>
<mx:FormItem label="City" width="100%">
<mx:TextInput id="_city" editable="false" width="100%"/>
</mx:FormItem>
</mx:Form>
<mx:HBox width="100%">
<mx:Label text="Insert a code to search" />
<mx:TextInput width="120" id="_searchCriteria" restrict="0-9" />
<mx:Button label="search" click="_presenter.recoverData()" />
</mx:HBox>

It also contains the methods defined in the IUserView and a private method that is registered as a listener for the creationComplete event that initialize the presenter

private function init():void{
_presenter = new UserViewPresenter(this);
}
public function set userName(value:String):void{
_userName.text = value;
}
public function set lastName(value:String):void{
_lastName.text = value;
}
public function set city(value:String):void{
_city.text = value;
}
public function get searchCriteria():String{
return _searchCriteria.text;
}
public function set errorMessage(value:String):void{
_errorMessage.text = value;
_errorMessage.visible = value != "";
}

As we already said the presenter is the one that handle with the business logic (in this Mickey Mouse sample we have simulated this with the XML data) and that update the view trough the interface without accessing directly the user interface elements.
In order to complete these tasks the presenter stores as a private member the view and perform the update accordingly to the result on the research on the XML file performed in the recoverData public method

public function recoverData():void{
if(_view.searchCriteria == ""){
_view.errorMessage = "Insert a code please!";
}else{
var data:XMLList = _xdata.customer.(@code == _view.searchCriteria);
if(data.length() == 0){
_view.errorMessage = "No user found!";
_view.userName = "";
_view.lastName = "";
_view.city = "";
}else{
_view.userName = data.firstName.text();
_view.lastName = data.lastName.text();
_view.city = data.city.text();
_view.errorMessage = "";
}
}

As you can see the MVP pattern it’s simple and powerful because it’s easy configurable in order to perform unit testing and because the presenter depends only on the view interface and not on the UI implementations. I really want to make a deeper post on the MVP in the next days discovering the the implementation of the Taligent’s one with Flex.