Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: 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 [email protected]

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.


IoT & Smart Cities Stories
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...