48

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?

5
  • Is this different from ORM and if so, where is the difference?
    – JB King
    Commented Nov 2, 2011 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) Commented Nov 2, 2011 at 15:39
  • 2
    I am really struggling to see how DataMapper is "something else entirely."
    – pdr
    Commented Nov 2, 2011 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. Commented Nov 2, 2011 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
    Commented Nov 2, 2011 at 19:10

6 Answers 6

27

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.

10
  • 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? Commented Nov 2, 2011 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
    Commented Nov 2, 2011 at 15:39
  • 8
    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
    Commented Nov 2, 2011 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
    Commented Nov 2, 2011 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
    Commented Nov 2, 2011 at 17:20
22

As I look over the answers I see the respondents all providing semantically incorrect answers. I think this is because you are all too focused on the question, which is focused on how mapper is related to factory or builder.

When in fact Mapper is NOT akin to factory or builder. Mapper is most like the adapter pattern (using GoF parlance). The adapter pattern provides functionality for converting one representation into another. The OP referred to the DataSet and the DataReader in ADO.NET-- well how about the SqlDataAdapter? The answer is in the name. Mapper is a new name for something that older programmers have known about for a long time: adapters.

Mapper converts one representation into another-- the very definition of the adapter pattern.

2
  • Its an old question but its not an adapter. You could say its a connector pattern because it connects things together. It can adapt to the other site but also transforms etc. Commented Mar 12, 2022 at 18:35
  • This should be the accepted answer, Mappers are closest to the Adapter pattern and are nothing like the builder or factory patterns.
    – YungDeiza
    Commented Dec 21, 2022 at 16:22
12

The only common thing about Mapper, Builder and Factory is that they deliver a "constructed product" - an 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 exactly the same as above - but the 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 need many seta 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 the same results?

However, the 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, the 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 the external data set to create the object as per the client is actually minimal. The Factory pattern really provides (as the name suggests) consistently similar product objects!

5

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

1
  • Sadly, the link is now broken.
    – Semmel
    Commented May 17 at 13:33
1

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).

0

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.

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