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.


@ThingsExpo Stories
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.