Design Patterns – Is ‘Mapper’ a Valid Design Pattern or a Variation of ‘Factory’?

design-patterns

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?

Best Answer

Although this is the first time I hear of the Mapper pattern, to me it sounds more like the Builder pattern rather than the Factory.

In the Factory pattern you encapsulate the logic for creating objects of a number of related classes. The prime example would be a situation where you need to create an object of a particular subclass of some abstract base class depending on some parameters. So a Factory always returns a pointer or a reference to the base class, but it actually creates an object of the appropriate derived class based on the parameters you give it.

In contrast, a Builder class always creates objects of the same class. You would use it if the creation of an object is complicated, e. g. its constructor takes lots of arguments, not all of which may be available instantly. So a builder object might be a place which stores the values for the constructor arguments until you have them all and are ready to create the "product", or it may provide reasonable default values and let you only specify the arguments whose values you need to change. A typical use case for the Builder pattern is for creating objects you might need in a unit test, to avoid cluttering the test code with all the creation logic.

To me a Mapper sounds like a variant of a Builder, where the constructor parameters come in the form of a database record or some other "raw" data structure.

Related Topic