Recently I worked on a project using Flex to create a front-end for Java-based Web Services. I ran into a favorite in the Java world: Transfer Objects/Value Objects. Early in the project, I was a bit skeptical of the transfer object model but, later on, I came to respect the value that it offers.
Transfer objects let two separate systems trade descriptive data objects without fear that either system will mistype the data or change the variable names. Transfer objects are an explicit agreement on how data will be encapsulated. They make integration easier because everyone can separate and build their system knowing what variable names and types will be traded. When someone modifies his version of the transfer object, the compile process should catch the changes and alert the file locations to fix the problems.
Flex automatically does the work of transferring a class type when using remote objects (one of the many reasons to use remote objects). However, when using SOAP Web Services, strong typing is broken because the class associations aren't automatically transferred to internal Flex classes. It's unfortunate, and leaves a bit of a gap when trying to use strong typing and compile-time error checking.
What's the value of strong typing? It makes it easier to debug the application. Instead of complaining at some obscure point when a user clicks on a certain button in the middle of a complicated workflow, it breaks during the compile process where the problem can be easily found and fixed. What could have been a two- hour search for a misnamed variable becomes a five-minute change.
The problem here though is how to get the untyped SOAP objects created by Flex into typed objects that Flex knows about - internal implementations of the transfer objects. The values themselves are typed, but there's no association between this data and the transfer object. Further, Flex can't be told that x SOAP object is actually of type y class. For example, trying to cast an incoming Web Service object into a user-defined TO class will cause a runtime error:
public var dpHistory:HistoryTo = event.result.HistoryTo as HistoryTo;
or
public var dpHistory:HistoryTo = HistoryTo(event.result.HistoryTo);
When I started trying to use strong typing of classes on the Flex side, I tried to do the transition by writing a custom transfer function for each type of class I had. For example:
var dpHistory:ArrayCollection = new ArrayCollection;
var tempObj:HistoryTo;
For (var i=0;i<webServiceReturn.result.HistoryTos.length; i++) {
tempObj = new HistoryTo;
tempobj.message = webServiceReturn.result.HistoryTos.getItemAt(i).message;
tempobj.objectName = webServiceReturn.result.HistoryTos.getItemAt(i).objectName;
.......
dpHistory.addItem(tempObj);
}
What a pain! It's error prone and doesn't allow for reuse. It's boring and adds to the amount of upkeep you have to do if anything changes. In the beginning, I avoided using transfer objects simply because that I didn't want to go through the pain of actually coding up every one of my Web Service returns like this. There are a lot of benefits to be gained by using transfer objects, but using the methodology above was horrible getting to them.
To me, the drawbacks (i.e., less code reuse, more duplicate coding, etc.) appeared to outweigh the benefits. Sure, these functions can be written up and saved as an ActionScript file somewhere and included when needed, but it looked like one transfer function was needed per transfer object. And that can be a real pain, especially in a large project with numerous transfer objects.
I figured there had to be a better way. After hunting around a bit, I came up with a solution that worked for my project. All that was needed was a generic object transfer utility to translate the incoming objects into typed classes that are created on the Flex side. Once the transfer objects have been written on the Flex side, then class introspection can be used to dynamically populate the values from untyped Web Service objects. Let me show you how I did it.
First off, create a transfer object class. One of the beautiful things about Flex is the automatic getters and setters for public variables on classes. This means that creating a transfer object can be very simple. Flex is flexible enough to use explicit getters and setters as public properties or to take public properties/variables and create automatic getters and setters for them. Creating custom transfer objects then becomes a breeze and literally takes just a few minutes to put together.
For example, a simple class might be a history display class:
package comp.myProject.to {
public class HistoryTo {
public var creationDate:Date = new Date;
public var message:String = new String;
public var objectName:String = new String;
public var objectType:String = new String;
public function HistoryTo() {
}
}
}
Once the custom class (transfer object) has been created on the Flex side, it can be used to store variables. Flex Builder knows about this class and can display hinting on the class names, warn when a property name has been misspelled, and make sure that the properties and values maintain their type across the application. The biggest challenge is filling the class with the proper information.
With a plain object or dynamic class, getting the dynamic values contained inside is done by looping through its properties (dynamic properties are values added to a dynamic class at runtime, like adding variables to a plain object). For example:
for (item in myObject) {
// do something here
myVar = myObject[item];
}
Unfortunately, classes don't support this method for finding static properties. This is where class introspection comes to the rescue. Class introspection returns a listing of all static properties of a class and the types of those properties. Best of all, class introspection is actually very easy in Flex. For example, there's a function in Flex that returns an XML structure of all the class properties:
import flash.utils.describeType;
var classInfo:XML = describeType(HistoryTo);
The function describeType returns an XML structure that can be looped over to get a listing of the public static properties, class methods, class name, and class base reference (if it extends a class). The function describeType won't return dynamic properties, private properties, or private functions. In the example, the classInfo variable now contains an XML object that can be looped through and/or treated like any other XML-type data source. For instance, it could output the results in a tree (a la the old object inspector for Flex 1.5). In this case, it can be used to loop through the Flex-side transfer classes, pull out the variables and types, check them against the Web Service objects, and transfer the Web Service object values to the appropriate class variables.
The root node contains the name of the class and the name of the class that it extends (if any):
var className:String = classInfo.@name;
To get the list of public variables on the class is relatively simple as well.
The classInfo..variable contains an array of variable names and variable types. Looping through them allows for assignment from one variable to the next:
var vName:String;
var vType:String;
for each (var v:XML in classInfo..variable) {
// set the xml name and type options to strings for easy comparison
vName = v.@Name;
vType = v.@Type;
//do something here
}
With a list of the variables on the class, loop through and assign values to the class variables. Looping through the known classes lets us look into the Web Service object to see if the variable is there. If the variable exists, then the value is automatically transferred to the class. Because internal classes are static, an error is thrown if an attempt is made to set a variable that hasn't been written into the class at compile time.
if (translateFrom.hasOwnProperty(vName) && translateFrom[vName] != null) {
// in the example, translateFrom is the incoming Web Service object or untyped object - check the incoming untyped
object to see if it has the property being looked for.
// do something here
}
From here, it's a matter of checking the type to transfer the variable accordingly. I've found some variable types from Java don't transfer over correctly. For example, longs sometimes don't transfer over as simple numbers and Booleans don't transfer over to a simple Boolean value. Sometimes they transfer over as a complexString value type that contains an XML snippet from the SOAP packet that Flex received. In most cases, when using the value in a complexString, it matches correctly and the fact that the object isn't strictly the type needed is barely noticeable. However, in certain cases, the difference becomes very noticeable. I've found that fixing it at the source helps eliminate problems down the road.
case "Number" :
translateTo[vName] = new Number(translateFrom[vName]);
// translateTo is the class that is being populated
break;
This object translator can be extended to work with an array of objects as well. Once the class is inspected, you can get the name of the class. This lets you create a reference to that class and thereby dynamically create new instances of that class:
var classRef:Class = Class(getDefinitionByName(className));
Then when looping through the array of class objects create a new class object to store the data for each object in the array. From the example code, arrayOfObjects is the incoming array, classinfo is the describeType xml:
if (arrayOfObjects != null) {
for (i=0;i<arrayOfObjects.length;i++) {
tempObj = new classRef();
returnArray.push(translateObject(arrayOfObjects[i],tempObj,classInfo));
}
}
Notice that most of the functions in the class are static functions:
public static function translateObject(translateFrom:Object,translateTo:
Object,classInfo:XML=null,upperCaseFromVar:Boolean=false):Object {
Making the class functions static means that they can be used without creating an instance of the class. Static functions aren't tied to any particular instance of the class, but to all instances of that class. In effect it becomes like any other utility class that Flex uses. An example of the difference between static functions and instance functions is best illustrated by the Date class. When using the date class to store date information an instance has to be created then functions are available to modify or get the information stored in that date object. For example:
var myDate:Date = new Date;
var myMonth:Number = myDate.getMonth;
The function getMonth is only available on an instance of the Date class. It uses information stored in that instance to return its value. The Date class also has a static function:
Date.parse()
The parse function is a static function available on the class itself, not on a particular instance. Likewise, once the object translator class is imported into the application file, any of its functions can be used from the class itself:
import comp.ebay.utils.ObectTranslator;
if (eventObj.result.HistoryTos != null ) {
dpHistory.source = ObjectTranslator.translateArrayObjects(eventObj.result.HistoryTos.source,HistoryTo);
}
This returns an array of objects. However, there are times when you have to translate a single object. The function, translateObject, returns a typed object under the guise of an untyped object. This is done so that any kind of class can be translated. If a type of class were typed for return on the translator object, it would only be able to translate that specific class (which would be of little value). Returning an untyped object allows for flexibility in what this function gets used for. Now casting the returned object as a specific class or transfer object will work because intrinsically it IS the internal transfer class that Flex knows about. For example:
var historyItem = HistoryTo(ObjectTranslator.translateObject(event.result,HistoryTo));
and
var historyItem = ObjectTranslator.translateObject(event.result,HistoryTo) as HistoryTo;
There's one additional benefit for ColdFusion users that can be gained from a generic object translator. Pre-ColdFusion 7.02 variable names are all uppercased when sent through Web Services. In the example objectTranslator class (see Listing 1) some quick code has been added that checks for uppercased variable names on incoming objects, moving them into the variable names of the correct case.
In summary, once all Web Service objects have been translated to internal classes, strong typing can be maintained by casting any Web Service objects to the transfer classes. If variable names on the transfer objects have to change (which they often do), it's a much smaller job to catch all of these problems at compile time than it is to debug and find them at runtime. In a language like Flex that's strongly typed, using transfer objects makes for more efficient use of time and energy. Problems can be caught sooner and with less impact to users. Using class introspection offers the ability to look into a class and see the properties and methods inside the class. Those properties can be used to fill transfer objects and eliminate much duplicate code.