Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
Is this different from ORM and if so, where is the difference? –  JB King Nov 2 '11 at 15:35
    
ORMs handle the mapping automatically for you - this is more for a scenario where you can't use an ORM (or have to write your own data layer/thin ORM) –  Wayne M Nov 2 '11 at 15:39
    
I am really struggling to see how DataMapper is "something else entirely." –  pdr Nov 2 '11 at 16:13
    
Maybe I'm mistaken - I thought the 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. –  Wayne M Nov 2 '11 at 17:45
    
martinfowler.com/eaaCatalog/dataMapper.html I sort of see what you mean but, reading that last paragraph, it's about right. Look at the PEAA Catalog. martinfowler.com/eaaCatalog/index.html. What you are describing is certainly a type of Mapper, and more closely fits DataMapper than the rest. –  pdr Nov 2 '11 at 19:10
add comment

5 Answers

up vote 13 down vote accepted

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.

share|improve this answer
    
Hmm I had heard of Builder but wasn't 100% aware of what it entailed - this helped clear things up! It almost sounds like the major difference is Factory returns an interface/abstract class that's really a concrete class based on parameters (if that made sense) while a Builder/Mapper takes actual data and maps those to properties, without much (if any) logic? –  Wayne M Nov 2 '11 at 15:23
1  
@Waine M: pretty much. Although there can be a lot of logic in a Builder, because the mapping of data to properties may not at all be straight forward. In fact, a builder may contain other builders to build the parameters. :) –  Dima Nov 2 '11 at 15:39
1  
The Builder pattern allows you to put all of the information required to build a complex (usually immutable) object over time and then instantiate the object at the end of the process. That's not what is happening here. –  pdr Nov 2 '11 at 15:48
    
+1 Agreed that this is a sensible approach, having a seperate 'mapper' class to act as a mediator between DTO objects and domain model objects. It also comes in handy when the domain model objects need to be put into some special state when being constructed (ie .NET ISupportInitialize interface). –  MattDavey Nov 2 '11 at 15:52
    
@pdr, I agree that a Mapper is not exactly like a builder, because all the data are available at once. But it is very similar, because it builds only one type of objects. –  Dima Nov 2 '11 at 17:20
show 4 more comments

The only common thing about Mapper, Builder and Factory is that they deliver a "constructed product" - and object instance of a type. To avoid any confusion, i am referring to following discussions for their respective definition.

  1. Mapper - close to what is explained here: http://www.codeproject.com/KB/library/AutoMapper.aspx. This is not exact same as above - but closest i found about mapper.

  2. Builder - as defined here: http://www.oodesign.com/builder-pattern.html

  3. Factory - is defined here: http://www.oodesign.com/factory-pattern.html

The mapper is essentially a constructor inside out. Suppose for a while, if you don't have a mapper - When you anyway need many set of parameters they are all arguments on the constructor. Now as things evolve, some applications are not aware of additional attributes that needs to go under constructor where one either computes it or use default. The critical thing is that mapper can do this for you - and it would be more useful if this has linkage to external objects to decide such an algorithm for construction.

The Builder is very different from mapper. A builder is essential when a complete object is composed using many parts of the object. It's kind of assembling the objects by fitting together many parts. Even the initialization of the individual part objects are related to existence of other parts.

The factory patterns looks very simple at the outset. It returns a newly constructed objects. If any ordinary constructor can give me a fully functional instance using an operator like new()? why would i need a factory that gives me same results?

However, factory pattern's usage is typically very specific; though most often, not displayed in literature where this is applied. Usually, an application creates a factory which is shared to various objects who needs to create such product objects during the execution. When many such products are created, Factory method allows creation of objects based on certain policy for example, one can force a certain template which is used by factory method when all objects are created. This is neither like a builder method; here product out is only one (and independent). This is also not like mapper; here external data set to create object as per the client is actually minimal. The factory pattern really provides (as the name suggests) a consistently similar product objects!

Dipan.

share|improve this answer
add comment

What your are doing here is actually some kind of type conversion (you convert your raw data into a business object). You can use the Factory Pattern for doing exactely that (i.e., type conversions), so yeah, in some kind of way, your class is a factory (though I would use a Static Factory for that).

share|improve this answer
add comment

the answer to your question : Is “Mapper” a valid design pattern ? is yes. Mapper pattern, is also known like Translator Pattern and is a documented pattern : http://www.iro.umontreal.ca/~keller/Layla/translator.pdf

share|improve this answer
add comment

Builders encapsulate complex business logic to build an object. Mapper on the other hand should just copy the fields from one to another.

For example map from Database Employee Object to Domain Employee Object, map from Domain Employee Object to Client Contract.

Builders on the other hand host multiple business decisions to build an object. From Single Responsibility point of view, this makes sense.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.