Welcome!

Victor Rasputnis

Subscribe to Victor Rasputnis: eMailAlertsEmail Alerts
Get Victor Rasputnis via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: XML Magazine, Clear Toolkit Magazine

XML: Article

Flex Best Practices: DTO is the Horseshoe of your Flex Application

Part 1: Data Transfer Objects is the right way of sending data over the network

Remember this old little rhyme?

For want of a nail, the shoe was lost;
For want of the shoe, the horse was lost;
For want of the horse, the rider was lost;
For want of the rider, the battle was lost;
For want of the battle, the kingdom was lost;
And all for the want of a horseshoe nail.

This little poem often comes to my mind as a see increasing number of amateurs perceiving Flex as yet another "library of controls".  The fact is, it is very easy to start coding in Flex. So much that hot-heads get on the coding spree before noticing that Flex is a beautifully crafted framework with profound cause and effect connections.
If I could pass just one Flex advice that would be: Use Data Transfer Objects.
Use custom Data Transfer Objects to pass data between server and Flash tiers of your Flex application. Do not use XML. Yes, I know that XML cool.  Do not use Objects. Yes, I know they are flexible.
Java programmers of all nations, do not use amorphous Map objects when talking to Flex. Make your Java methods accept and return custom classes and collections of custom classes, but not collections of Maps.
Here are the details:

1. DO define peer classes in ActionScript…

package datasource.dto {
    [RemoteClass(alias="datasource.dto.CustomerDTO")]
    public class CustomerDTO {
        public  var firstName : String;
        public  var birthDate: Date;
    }
}

…and Java

public class CustomerDTO {
    public String firstName;
    public java.util.Date birthDate;
}   

You get immediate benefits right there: Intellisense prompt on your properties and the ability to re-factor your code.

2.  DO make the properties of these classes bindable, as long as you foresee run-time updates. Then,  do use collections of these classes as dataProviders for controls like DataGrid and let Flex do the “miracle”: all changes to the data will be reflected by the visual control.
How do you make the property bindable?  It’s easy.  Put  [Bindable] in front of the property declaration. Or, with a wide brush, in front of the class declaration:

package datasource.dto {
    [RemoteClass(alias="datasource.dto.CustomerDTO")]
    [Bindable]
    public class CustomerDTO {
        public  var firstName : String;
        public  var birthDate: Date;
    }
}
You do that and every change of a property of the  class  will result in the event that a Flex collection is eagerly listening to. Then, the collection, will dispatch another, different event, that a Flex DataGrid is eagerly listening to.  That is the simple mechanics behind the “miracle”.
 Now imagine what happens when your property is not bindable. Your code updates the property, but the DataGrid is stale. Still, when you scroll it re-paints  the change. You reach to Flex documentation and find collection.refresh() method as a rescue. You look a bit more and find another savior: itemUpdated(). This one is a real gem: every time you touch the property, you have the rights to remain talkative and inform the collection that you have just modified it. Let's talk robustness, shall we?

Get on DTO path and itemUpdated() should sound to you like some undocumented event .
I almost hear: wait, a minute! Our Objects work fine for us. Indeed, Flex attempts "no child left behind" logic even if you do not have DTOs. The default setting of RemoteObject, makeObjectsBindable =  true, causes Flex to convert Objects to bindable ObjectProxy objecs. Alas! ObjectProxy helps only on  the first level of properties. So, for instance, if your property is an Array, the reference to Array will become bindable, but none of the items will.
Do it the right way: use DTO.

3. Make sure that your server-side and client-side DTOs  DO provide unique set/get uuid property.  Flex loves this property, do get in love with it too. Flex is using it to identify elements of data presented by the list-based controls. You will find numerous uses for it as well. For instance,  instead of sorting by industry, ticker you would sort by industry, ticker and uuid. Why? Because then the hash value will be unique for each record, which would result in substantially better performance.

4. DO NOT hunt for value change on the visual controls (aka View). This task belongs to the data layer (aka Model). Consider replacing public var with the get/set property pair and dispatching the event  (PropertyChange) yourself. Once you do that,  you can intercept (trace, log, place breakpoint) all changes to the data.

    [Bindable(event="propertyChange")]
    public dynamic class PortfolioItemDTO extends EventDispatcher
    {
        private  var _lastPrice:Number;
        public  function set lastPrice( value : Number):void{
            var oldValue:Object = _lastPrice;
            if (oldValue !== value)   {
                _lastPrice = value;
                dispatchUpdateEvent("lastPrice", oldValue, value);
            }
        }

        public  function get lastPrice() : String{
            return _lastPrice;
        }

    pPrivate  function dispatchUpdateEvent(propertyName:String, oldValue:Object,  
value:Object):void {
            dispatchEvent(
                PropertyChangeEvent.createUpdateEvent(this, propertyName, oldValue,     
        value)
                );
            }

    }

Beware of the devil. It’s  in the details.  Do watch the tiny difference between Bindable(event="propertyChange")] and [Bindable].  The former syntax tells to Flex compiler: “Look ma, a bindable property!” and Flex generates code to watch the propertyChange event. The latter syntax forces Flex compiler to actually produce the event. How? Compiler replaces your property with a setter/getter pair where the setter’s role is to dispatch the event.  What if your code have taken care of event dispatching already? It does not matter to Flex. So, if you use wrong syntax you may wind up with events being dispatched twice!

5. DO consider DTO extension layer for customization purposes. For instance, you may introduce "computed column":
package datasource.dto {
    [RemoteClass(alias="datasource.dto.CustomerDTO")]
    public class PortfolioItemExtendedDTO extends PortfolioItemDTO

    public function get unrealizedGain():Number {
        return lastPrice - costBasis;
    }

DO NOT use DataGrid's itemEditEnd for similar purposes. Work with the Model. Leave the View layer alone.

DO NOT be afraid of two ActionScript classes mapping (via [RemoteClass]) to the same Java DTO, such as datasource.dto.CustomerDTO in our case. Flex code-generator is smart enough to fancy the extension layer.
Again, to guarantee that Flex will "feel" the change of the computed property unrealizedGain, DO mark it as [Bindable]. You would need a dummy setter to lead Flex compiler to believe that the property is going to dispatch change events; meanwhile the real cause of event will be either lastPrice or costBasis, of course:

    [Bindable(event="propertyChange")]
    public function get unrealizedGain():Number {
        return lastPrice - costBasis;
    }
    public function set unrealizedGain(value:Number):void {
        // Ain't gonna happen, but Flex won't consider Bindable without the setter
    }

Over the project’s lifespan, you will see many additional fits for DTOs: custom serialization, custom  toString() and toXML() methods. With DTO your architecture will be reliable, performing and you will  save tons of time and energy. Think of the DTO as the horseshoe of your Flex project.

More Stories By Victor Rasputnis

Dr. Victor Rasputnis is a Managing Principal of Farata Systems. He's responsible for providing architectural design, implementation management and mentoring to companies migrating to XML Internet technologies. He holds a PhD in computer science from the Moscow Institute of Robotics. You can reach him at vrasputnis@faratasystems.com

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.