Mike Orth – Booya!

Flex, Actionscript

Object Translator – Normalizing Objects

This is an extension of a great blog from Justin Opitz on normalizing value objects.  We were discussing the a best way to take objects that are somewhat similar in form and conform them to an interface. Normalizing objects allows you perform logic on data that is generic and more makes your code more reusable.

So imagine we have several different object types coming in, like Artist, Album, & Track objects with properties that are similar, yet unique, including “artistName”, “albumName”, “trackName”, among others. We want to put this into a VO with just “name”.

Below is a modified version of the translator. If you have several different VOs that implement an interface then you may want the ability to assign them as needed. Since it could be any one of the VOs being, we’ll pass it in as a wild card

vo:*"

and then return the newly assigned object. Also, if the current propety doesn’t match a pattern we’re looking for, then it assigns it as-is.

So here’s what the function will look like:

public static function TranslateObject ( targetObject:Object, vo:* ):*
{

for (var s:String in vo)
{
//we are going to check each prop name to see if there is a match for our
//targetObject’s known properties
//obvious ly this list will grow the more props you have to normalize
//however it only grows once regardless of the number of non-normalized VOs

if (s.toLowerCase().indexOf(’name’) != -1)
targetObject.name = String(vo[s]);

else if (s.toLowerCase().indexOf(’id’) != -1)
targetObject.id = int(vo[s]);

else if (s.lowerCase().indexOf(’genres’) != -1)
targetObject.genres = vo[s] as Array;

else
targetObject[s] = vo[s];

return vo;
}
}

1 comment

1 Comment so far

  1. jwopitz July 30th, 2008 9:43 am

    one thing I would do is check the targetObject for the property in question in the last else block:

    else
    {
    if (targetObject.hasOwnProperty(s))
    targetObject[s] = vo[s];
    }

    So as to not encounter any RTEs and null pointer exceptions.

Leave a reply

Spam Protection by WP-SpamFree

Mexico

Google Tracking Code