Programming Search⌘K

Patternadvanced

Mapper

Also called Mapper pattern, object mapper, translation layer.

A mapper is an object that connects two independent subsystems, so that they work together while neither of them knows the other or the mapper.

Family
architectural
Intent
Set up the communication between two independent objects or subsystems that must stay unaware of each other.

Intent

A mapper is "An object that sets up a communication between two independent objects."1 The mapper knows both sides. The two sides do not know each other, and they do not know the mapper.

Problem

Fowler describes the problem: "Sometimes you need to set up communications between two subsystems that still need to stay ignorant of each other."1 One subsystem can be code that the team cannot change, such as a library or a legacy system. The two subsystems can have different names and types for the same things. A product can be pen in one and PEN-01 in the other.

If one subsystem calls the other directly, it must know the names and types of the other, and it can no longer change or be used alone. The catalog adds that you may not want "to create dependencies between the two or even between them and the isolating element."1

Solution

Put a third object between the subsystems. The parts are:

  • The two subsystems. Each one has its own types and its own interface, and neither one imports the other.
  • The mapper. It reads the data of one side, converts the names, the types and the structure, and calls the other side. It converts the reply back in the same way.
  • The trigger. Something outside both subsystems calls the mapper, for example the application layer or a scheduled job. This is the difference from a Gateway, which its client calls and so knows.
  Order (pen x2, ink x1)         OrderWarehouseMapper              Warehouse
  status "new"          <-reads- converts pen -> PEN-01   -calls-> pick(ref ORD-7,
                                 converts PICKED -> picked <-reply-     PEN-01 x2, INK-02 x1)
  status "picked"       <-sets--

In the following program, a thermometer and a display do not know each other. The mapper reads one and writes to the other.

class Thermometer:  # one subsystem: knows only degrees Celsius
    def read(self):
        return 21.5


class Display:  # another subsystem: knows only text
    def show(self, text):
        print("display:", text)


class ThermometerDisplayMapper:  # knows both; neither knows the mapper
    def __init__(self, thermometer, display):
        self.thermometer, self.display = thermometer, display

    def update(self):
        self.display.show(f"{self.thermometer.read():.1f} C")


ThermometerDisplayMapper(Thermometer(), Display()).update()
Output
display: 21.5 C

Example

Each example file has an order system with an Order of item names and quantities, and a warehouse that works only with product codes and reference strings. The mapper OrderWarehouseMapper builds a pick request with the reference ORD-7 and the codes PEN-01 and INK-02, sends it to the warehouse, and converts the state PICKED of the reply into the status picked of the order. The order system and the warehouse have no reference to each other or to the mapper.

PythonGitHub
# Subsystem 1: the order system. It knows nothing about the warehouse.
class Order:
    def __init__(self, number, customer, lines):
        self.number, self.customer, self.lines = number, customer, lines  # lines: (item, qty)
        self.status = "new"


# Subsystem 2: the warehouse. It knows nothing about orders. It works with
# product codes and reference strings, and it cannot be changed.
class Warehouse:
    CODES = {"PEN-01", "INK-02"}

    def pick(self, request):
        known = [(code, qty) for code, qty in request["lines"] if code in self.CODES]
        return {"ref": request["ref"], "state": "PICKED" if len(known) == len(request["lines"]) else "SHORT"}


# The mapper knows both subsystems and connects them. Neither of them knows the mapper.
class OrderWarehouseMapper:
    CODE_OF = {"pen": "PEN-01", "ink": "INK-02"}
    STATUS_OF = {"PICKED": "picked", "SHORT": "waiting for stock"}

    def __init__(self, warehouse):
        self.warehouse = warehouse

    def send(self, order):
        request = {"ref": f"ORD-{order.number}",
                   "lines": [(self.CODE_OF[item], qty) for item, qty in order.lines]}
        print("warehouse gets: ref", request["ref"] + ", lines",
              ", ".join(f"{code} x{qty}" for code, qty in request["lines"]))
        reply = self.warehouse.pick(request)
        print("warehouse replies: ref", reply["ref"] + ", state", reply["state"])
        order.status = self.STATUS_OF[reply["state"]]


order = Order(7, "ann", [("pen", 2), ("ink", 1)])
print(f"order {order.number} for {order.customer}:",
      ", ".join(f"{qty} x {item}" for item, qty in order.lines) + f", status {order.status}")
OrderWarehouseMapper(Warehouse()).send(order)
print(f"order {order.number} status: {order.status}")
Output
order 7 for ann: 2 x pen, 1 x ink, status new
warehouse gets: ref ORD-7, lines PEN-01 x2, INK-02 x1
warehouse replies: ref ORD-7, state PICKED
order 7 status: picked
  • Verdict: idiom. The mapper is a normal class with two tables, CODE_OF for the item names and STATUS_OF for the states. Order and Warehouse have no import or reference to each other or to the mapper.
  • The mapper is the only code that changes when the warehouse gets new product codes.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {
    // Subsystem 1: the order system. It knows nothing about the warehouse.
    record OrderLine(String item, int qty) {}

    static class Order {
        final int number;
        final String customer;
        final List<OrderLine> lines;
        String status = "new";
        Order(int number, String customer, List<OrderLine> lines) {
            this.number = number; this.customer = customer; this.lines = lines;
        }
    }

    // Subsystem 2: the warehouse. It knows nothing about orders. It works with
    // product codes and reference strings, and it cannot be changed.
    record PickLine(String code, int qty) {}
    record PickRequest(String ref, List<PickLine> lines) {}
    record PickReply(String ref, String state) {}

    static class Warehouse {
        static final Set<String> CODES = Set.of("PEN-01", "INK-02");
        PickReply pick(PickRequest request) {
            long known = request.lines().stream().filter(l -> CODES.contains(l.code())).count();
            return new PickReply(request.ref(), known == request.lines().size() ? "PICKED" : "SHORT");
        }
    }

    // The mapper knows both subsystems and connects them. Neither of them knows the mapper.
    static class OrderWarehouseMapper {
        static final Map<String, String> CODE_OF = Map.of("pen", "PEN-01", "ink", "INK-02");
        static final Map<String, String> STATUS_OF = Map.of("PICKED", "picked", "SHORT", "waiting for stock");
        private final Warehouse warehouse;
        OrderWarehouseMapper(Warehouse warehouse) { this.warehouse = warehouse; }

        void send(Order order) {
            List<PickLine> lines = new ArrayList<>();
            for (OrderLine l : order.lines) lines.add(new PickLine(CODE_OF.get(l.item()), l.qty()));
            PickRequest request = new PickRequest("ORD-" + order.number, lines);
            System.out.println("warehouse gets: ref " + request.ref() + ", lines "
                + lines.stream().map(l -> l.code() + " x" + l.qty()).collect(Collectors.joining(", ")));
            PickReply reply = warehouse.pick(request);
            System.out.println("warehouse replies: ref " + reply.ref() + ", state " + reply.state());
            order.status = STATUS_OF.get(reply.state());
        }
    }

    public static void main(String[] args) {
        Order order = new Order(7, "ann", List.of(new OrderLine("pen", 2), new OrderLine("ink", 1)));
        System.out.println("order " + order.number + " for " + order.customer + ": "
            + order.lines.stream().map(l -> l.qty() + " x " + l.item()).collect(Collectors.joining(", "))
            + ", status " + order.status);
        new OrderWarehouseMapper(new Warehouse()).send(order);
        System.out.println("order " + order.number + " status: " + order.status);
    }
}
Output
order 7 for ann: 2 x pen, 1 x ink, status new
warehouse gets: ref ORD-7, lines PEN-01 x2, INK-02 x1
warehouse replies: ref ORD-7, state PICKED
order 7 status: picked
  • Verdict: idiom. The records PickLine, PickRequest and PickReply (Java 16 or later) are the types of the warehouse, and OrderLine is the type of the order system. Only OrderWarehouseMapper uses both.
  • In a real program, a library such as MapStruct can generate the copy of the fields, and the mapper keeps the rules that are not a plain copy.
JavaScriptGitHub
// Subsystem 1: the order system. It knows nothing about the warehouse.
class Order {
  constructor(number, customer, lines) {
    this.number = number;
    this.customer = customer;
    this.lines = lines; // [item, qty]
    this.status = "new";
  }
}

// Subsystem 2: the warehouse. It knows nothing about orders. It works with
// product codes and reference strings, and it cannot be changed.
class Warehouse {
  static CODES = new Set(["PEN-01", "INK-02"]);

  pick(request) {
    const known = request.lines.filter(([code]) => Warehouse.CODES.has(code));
    return { ref: request.ref, state: known.length === request.lines.length ? "PICKED" : "SHORT" };
  }
}

// The mapper knows both subsystems and connects them. Neither of them knows the mapper.
class OrderWarehouseMapper {
  static CODE_OF = { pen: "PEN-01", ink: "INK-02" };
  static STATUS_OF = { PICKED: "picked", SHORT: "waiting for stock" };

  constructor(warehouse) {
    this.warehouse = warehouse;
  }

  send(order) {
    const request = {
      ref: `ORD-${order.number}`,
      lines: order.lines.map(([item, qty]) => [OrderWarehouseMapper.CODE_OF[item], qty]),
    };
    const lines = request.lines.map(([code, qty]) => `${code} x${qty}`).join(", ");
    console.log(`warehouse gets: ref ${request.ref}, lines ${lines}`);
    const reply = this.warehouse.pick(request);
    console.log(`warehouse replies: ref ${reply.ref}, state ${reply.state}`);
    order.status = OrderWarehouseMapper.STATUS_OF[reply.state];
  }
}

const order = new Order(7, "ann", [["pen", 2], ["ink", 1]]);
const lines = order.lines.map(([item, qty]) => `${qty} x ${item}`).join(", ");
console.log(`order ${order.number} for ${order.customer}: ${lines}, status ${order.status}`);
new OrderWarehouseMapper(new Warehouse()).send(order);
console.log(`order ${order.number} status: ${order.status}`);
Output
order 7 for ann: 2 x pen, 1 x ink, status new
warehouse gets: ref ORD-7, lines PEN-01 x2, INK-02 x1
warehouse replies: ref ORD-7, state PICKED
order 7 status: picked
  • Verdict: idiom. The tables of the mapper are static fields. The request and the reply are plain objects, the format of the warehouse.
package main

import (
	"fmt"
	"strings"
)

// Subsystem 1: the order system. It knows nothing about the warehouse.

type orderLine struct {
	item string
	qty  int
}

type Order struct {
	Number   int
	Customer string
	Lines    []orderLine
	Status   string
}

// Subsystem 2: the warehouse. It knows nothing about orders. It works with
// product codes and reference strings, and it cannot be changed.

type pickLine struct {
	code string
	qty  int
}

type pickRequest struct {
	ref   string
	lines []pickLine
}

type pickReply struct{ ref, state string }

type Warehouse struct{}

var codes = map[string]bool{"PEN-01": true, "INK-02": true}

func (Warehouse) Pick(r pickRequest) pickReply {
	known := 0
	for _, l := range r.lines {
		if codes[l.code] {
			known++
		}
	}
	state := "SHORT"
	if known == len(r.lines) {
		state = "PICKED"
	}
	return pickReply{r.ref, state}
}

// OrderWarehouseMapper knows both subsystems and connects them.
// Neither of them knows the mapper.
type OrderWarehouseMapper struct{ warehouse Warehouse }

var codeOf = map[string]string{"pen": "PEN-01", "ink": "INK-02"}
var statusOf = map[string]string{"PICKED": "picked", "SHORT": "waiting for stock"}

func (m OrderWarehouseMapper) Send(o *Order) {
	req := pickRequest{ref: fmt.Sprintf("ORD-%d", o.Number)}
	var parts []string
	for _, l := range o.Lines {
		req.lines = append(req.lines, pickLine{codeOf[l.item], l.qty})
		parts = append(parts, fmt.Sprintf("%s x%d", codeOf[l.item], l.qty))
	}
	fmt.Printf("warehouse gets: ref %s, lines %s\n", req.ref, strings.Join(parts, ", "))
	reply := m.warehouse.Pick(req)
	fmt.Printf("warehouse replies: ref %s, state %s\n", reply.ref, reply.state)
	o.Status = statusOf[reply.state]
}

func main() {
	order := &Order{7, "ann", []orderLine{{"pen", 2}, {"ink", 1}}, "new"}
	var parts []string
	for _, l := range order.Lines {
		parts = append(parts, fmt.Sprintf("%d x %s", l.qty, l.item))
	}
	fmt.Printf("order %d for %s: %s, status %s\n", order.Number, order.Customer, strings.Join(parts, ", "), order.Status)
	OrderWarehouseMapper{Warehouse{}}.Send(order)
	fmt.Printf("order %d status: %s\n", order.Number, order.Status)
}
Output
order 7 for ann: 2 x pen, 1 x ink, status new
warehouse gets: ref ORD-7, lines PEN-01 x2, INK-02 x1
warehouse replies: ref ORD-7, state PICKED
order 7 status: picked
  • Verdict: idiom. In a real program, the order system and the warehouse are two packages, and the mapper is a third package that imports both. Neither of the two imports the mapper.
  • Send takes a pointer to the order, so that it can set the status.
RustGitHub
// Subsystem 1: the order system. It knows nothing about the warehouse.
struct Order {
    number: u32,
    customer: String,
    lines: Vec<(String, u32)>, // (item, qty)
    status: String,
}

// Subsystem 2: the warehouse. It knows nothing about orders. It works with
// product codes and reference strings, and it cannot be changed.
struct PickRequest {
    reference: String,
    lines: Vec<(String, u32)>, // (code, qty)
}

struct PickReply {
    reference: String,
    state: &'static str,
}

struct Warehouse;

impl Warehouse {
    const CODES: [&'static str; 2] = ["PEN-01", "INK-02"];

    fn pick(&self, request: &PickRequest) -> PickReply {
        let known = request.lines.iter().filter(|(c, _)| Self::CODES.contains(&c.as_str())).count();
        let state = if known == request.lines.len() { "PICKED" } else { "SHORT" };
        PickReply { reference: request.reference.clone(), state }
    }
}

// The mapper knows both subsystems and connects them. Neither of them knows the mapper.
struct OrderWarehouseMapper {
    warehouse: Warehouse,
}

impl OrderWarehouseMapper {
    fn code_of(item: &str) -> &'static str {
        match item {
            "pen" => "PEN-01",
            "ink" => "INK-02",
            _ => "UNKNOWN",
        }
    }

    fn status_of(state: &str) -> &'static str {
        if state == "PICKED" { "picked" } else { "waiting for stock" }
    }

    fn send(&self, order: &mut Order) {
        let request = PickRequest {
            reference: format!("ORD-{}", order.number),
            lines: order.lines.iter().map(|(i, q)| (Self::code_of(i).to_string(), *q)).collect(),
        };
        let lines: Vec<String> = request.lines.iter().map(|(c, q)| format!("{} x{}", c, q)).collect();
        println!("warehouse gets: ref {}, lines {}", request.reference, lines.join(", "));
        let reply = self.warehouse.pick(&request);
        println!("warehouse replies: ref {}, state {}", reply.reference, reply.state);
        order.status = Self::status_of(reply.state).to_string();
    }
}

fn main() {
    let mut order = Order {
        number: 7,
        customer: "ann".to_string(),
        lines: vec![("pen".to_string(), 2), ("ink".to_string(), 1)],
        status: "new".to_string(),
    };
    let lines: Vec<String> = order.lines.iter().map(|(i, q)| format!("{} x {}", q, i)).collect();
    println!("order {} for {}: {}, status {}", order.number, order.customer, lines.join(", "), order.status);
    OrderWarehouseMapper { warehouse: Warehouse }.send(&mut order);
    println!("order {} status: {}", order.number, order.status);
}
Output
order 7 for ann: 2 x pen, 1 x ink, status new
warehouse gets: ref ORD-7, lines PEN-01 x2, INK-02 x1
warehouse replies: ref ORD-7, state PICKED
order 7 status: picked
  • Verdict: idiom. code_of and status_of are match expressions. send takes &mut Order, so the borrow checker shows that only the mapper changes the order.

Consequences

Benefits.

  • The subsystems stay independent. Each one can change, be tested and be used alone. A change of one changes only the mapper.
  • One place for the translation. All the knowledge of how the two sides fit together is in the mapper.
  • Code that cannot change can still work together. The mapper connects a library or a legacy system with no change to it.

Liabilities.

Without a mapper, the names of one subsystem reach the other. In the following program, the order system passes its item names to the warehouse, which knows only codes, and the warehouse can pick nothing.

This code runs but gives a wrong answer on purpose.

class Warehouse:  # knows only product codes
    def pick(self, lines):
        codes = {"PEN-01", "INK-02"}
        return sum(1 for code, qty in lines if code in codes)


# No mapper: the order system passes its own item names to the warehouse.
lines = [("pen", 2), ("ink", 1)]
print("lines that the warehouse can pick:", Warehouse().pick(lines), "of", len(lines))
Output
lines that the warehouse can pick: 0 of 2

Put the conversion from item names to codes in a mapper, and let the mapper call the warehouse.

A third piece to keep in step. The mapper depends on both subsystems, so a change of either one can break it, and the tests of the mapper need both sides.

The mapper must be called. Because neither side knows the mapper, some other code must decide when to call it.

When not to use it

When one side can depend on the other. If the order system may know the warehouse, a Gateway in the order system is simpler.

When the two sides already use the same types. Then there is nothing to translate.

Data mapper. The best known mapper is the Data Mapper, which moves data between domain objects and the database while each one is unaware of the other.2

Mapping libraries. A library can generate the code that copies fields from one type to another, for example from a domain object to a Data transfer object. "MapStruct is a Java annotation processor for the generation of type-safe bean mapping classes."3

Gateway and mediator. A Gateway is called by its client, which knows it. A Mediator pattern connects many objects, which know the mediator. A mapper connects two sides that know neither each other nor the mapper.

Known uses

  • The Data Mapper of object-relational mapping tools connects the domain objects and the database tables.2
  • MapStruct generates mapping classes between Java bean types with an annotation processor. The generated code copies the values with plain getter and setter calls, not with reflection.3

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Mapper, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Mapper; Chapter 18, Base Patterns, Mapper
  3. MapStruct reference guide, Preface; Introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/34ESVJ/text.yaml