Working with Remote Object Service invocation utilizing binary connection such as AMFPHP or others, it is often challenging to map the server data with the client data, even when the object is identical in terms of object properties. When you try to cast the object you get a null VO. The reason is that the run-time compiler is unable to cast the object to the VO type.
I was surprised to see experienced Flex developers manually mapping objects directly or creating constructors to the VO to map every single property. Here’s what we shouldn’t do:
var result:ResultEvent = data as ResultEvent; var user:UserVO = new UserVO(); user.fname = result.result[0].fname; user.lname = result.result[0].lname; user.email = result.result[0].email; etc...
The reason we don’t want to do that, is that this type of approach can work well on a simple VO, however when we have a complex VO with many properties, the code starts to look unprofessional.
I think that as engineers many times we are not sure what’s the best approach/practices, but we can certainly identify wrong approaches. For instance, when we find ourselves doing copy pasting we certainty should find a new approach or if there is no approach available, we can develop our own tool/API to handle the use case.
The right approach is to declare a static method that takes a VO object of type “*” since we don’t know the VO type. Iterate through the collection and map the properties and than return the VO back. Here’s a small utility to handle the mapping:
/*
Copyright (c) 2008 Elrom LLC. All Rights Reserved
@author Elad Elrom
@contact elad.ny@gmail.com
@internal
*/
package com.elad.framework.utils
{
public final class VOHelper
{
/**
* Method to mpa an object to a VO type. The are cases where the object returned from the service cannot
* cast as the type of VO, this static method will allow you map the VO.
*
* @example: var user:UserVO = VOHelper.ConvertObjecToVO(result.result[0], new UserVO() );
*
* @param ob the object returned from the server.
* @return return the VO object. Since we want to use many types of VO we use * to generate it dynamically.
*
*/
public static function ConvertObjecToVO(ob:Object, vo:*):*
{
for(var parameter:String in ob)
{
try
{
vo[ parameter.toLowerCase() ] = ob[ parameter ];
}
catch( err:Error )
{
}
}
return vo;
}
}
}
Now you can just use the utility to map the object;
var user:UserVO = VOHelper.ConvertObjecToVO(result.result[0], new UserVO() );





















