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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
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...
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...
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...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
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...