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;
}
4 Comments so far
Leave a comment
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

[...] 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 [...]
Pingback by Mike Orth - Booya! » Object Translator - Normalizing Objects Wednesday, July 30, 2008 @ 1:17 amThanks!
Comment by ADRIAN DESS Friday, August 29, 2008 @ 4:43 pmnice!
Comment by Bob Sunday, November 9, 2008 @ 3:18 pmthank’s!
Comment by Bill Sunday, November 9, 2008 @ 3:20 pm