A common pattern I see is what's known as the Mapper
pattern (not to be confused with DataMapper
which is something else entirely), which takes as an argument some kind of "raw" data source (e.g. an ADO.NET DataReader
or DataSet
) and maps the fields to properties on a business/domain object. Example:
class PersonMapper
{
public Person Map(DataSet ds)
{
Person p = new Person();
p.FirstName = ds.Tables[0].Rows[0]["FirstName"].ToString();
// other properties...
return p;
}
}
The idea being your Gateway/DAO/Repository/etc. will call into the Mapper before it returns, so you get a rich business object versus the underlying data container.
However, this seems to be related, if not identical, to the Factory pattern (in the DDD parlance, anyways), which constructs and returns a domain object. Wikipedia says this re: the DDD Factory:
Factory: methods for creating domain objects should delegate to a specialized Factory object such that alternative implementations may be easily interchanged.
From that quote the only difference I could think of is that the DDD-style Factory could be parameterized so it could return a specialized type of object if the need arose (e.g. BusinessCustomer versus ResidentialCustomer) while the "Mapper" is keyed to a specific class and only does translation.
So is there a difference between these two patterns or are they essentially the same thing with different names?
DataMapper
pattern did the database access itself, while this "Mapper" doesn't pull from the database, just converts a result set of some kind into an object.