explorers' club

explorations in dev, science, sci-fi, games, and other fun stuff!

Normalizing Value Objects: Quick Tip

4 Comments

A buddy of mine asked me the other day if I had any thoughts on normalizing value objects coming in from various services.  For example say you have at least 3 different objects that all share similar properties but aren’t quite named the same thing for convenience sake.  Let’s assume that your service guy is simply assembling objects straight from the database table and using their column names rather than normalizing it for you.  Here are the sample objects:

ArtistObject
{
     artistName:String
     artistId:int
     artistGenres:Array
}

AlbumObject
{
     albumName:String
     albumId:int
     albumGenres:Array
}

TrackObject
{
     trackName:String
     trackId:int
     trackGenres:Array
}

And let’s say you want to normalize those incoming objects to an interface like so:

IMediaObject
{
     name:String
     id:int
     genres:Array
}

Your first inclination may be to use an else..if statement to cycle thru the variou value object types that may be expected in a given response (assuming you are not doing low-level CRUD services and are actually leveraging services for various purposes) like so:

if (vo is ArtistObject)
{ ... }
else if (vo is AlbumObject)
{ ... }
else if (vo is TrackObject)
{ ... }
else if .... you get the point

Here is an often overlooked but extremely useful operation that will eliminate lengthy else..if loops while allowing you to cycle thru known properties to retrieve non-normalized property values.

var targetObject:IMediaObject = //whatever you are normalizing to
var vo:Object = serviceResponse.data //the object returned from your service
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
   //obviously 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]);

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

   if (s.lowerCase().indexOf('genres') != -1)
      targetObject.genres = vo[s] as Array;
}
Advertisements

4 thoughts on “Normalizing Value Objects: Quick Tip

  1. Pingback: Mike Orth - Booya! » Object Translator - Normalizing Objects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s