views:

40

answers:

1

Hello,

I have a class called User defined using MooTools Class. This class contains a getter called fullName (which manipulates firstName and lastName).

var User = new Class({
 initialize:function(firstName, lastName){
  this.firstName = firstName;
  this.lastName = lastName;
 },
 fullName:function(){
  return this.firstName + ' ' + this.lastName;
 }
});

I can request a list of user profiles from the Java backend via AJAX and obtain a JSON response, basically a Javascript Array of Objects.

[{firstName:'John', lastName:'Doe'},{firstName:'Bob', lastName:'Hope'},....]

Is there a recommended way to convert this Array of DTOs into MooTools User Classes?

I could use Array.each and create a new instance of User by passing each DTO's firstName and lastName value in the constructor. Or maybe pass the DTO itself and use:

$each(userDTO,function(value,key){...}

I'm looking at $extend(myClass, myDTO) which copies the properties of myDTO into myClass. Seems to be the easiest option at present.

It would be nice to know the recommended way to copy the DTO values. Many thanks!

+2  A: 

Personally, I would write a function to convert a DTO to an User and then map the list of DTOs through that function:

var dtos = ...
var f = function(dto) { return new User(dto.firstName,dto.lastName) };
var users = dtos.map(f);

This is a common approach in other languages (could be classified as an instance of the "factory method" pattern) - I see no reason not to use it in javascript too.

It may seem less "cool" than (eg):

var users = dtos.map(function(dto){ return $extend(new User(),dto); });

but DTOs may be subject to change (renamed, removed or - most probably - added fields) and having those changes automatically (ie: uncontrolledly) propagated to your classes is rarely a good idea.

Also, putting all knowledge on how to convert a DTO to a User in a single "place" is a Good Thing architecture-wise.

giorgiga
Agreed! I like the function/map approach and can choose between constructor or $extend approach.
Riaz