Patterncore
Gateway
Also called Gateway pattern, wrapper of an external system, client wrapper.
A gateway is an object that wraps the access to an external system or resource, so that the rest of the program calls it in its own terms and not in the terms of the foreign API.
- Family
- architectural
- Intent
- Encapsulate the access to an external system or resource in one object with an interface in the terms of the program.
Intent
A gateway is "An object that encapsulates access to an external system or resource."1 The rest of the program calls the gateway in its own terms. Only the gateway knows the foreign API.
Problem
Most programs use external systems: a database, a remote service, a file format, a library with an awkward API. That API is made for the external system, not for the program. Fowler writes that it "may use different types, require strange arguments, combine fields in ways that don't make sense in our context."2
If each part of the program calls the foreign API directly, the knowledge of that API spreads through the code. Each caller must convert the units, read the return codes and handle the errors, and each caller can do it differently. A change of the external system then needs a change in each caller, and a test cannot run without the external system.
Solution
Put all the code that knows the foreign API into one object, the gateway. Give it an interface in the terms of the program. The parts are:
- The gateway interface. Methods with the names, types and errors of the program, made for what the program needs, and not for all that the external system can do.
- The translation. The gateway converts each call into the call of the foreign API and converts the result back. Fowler says that "Gateways should only include logic that supports this translation between domestic and foreign concepts."2
- The connection. An optional small object that only makes the call to the foreign code. Fowler notes that it "acts as a good point for inserting a Test Double".2
program code --standard_cost(1.2 kg, "DE")--> ShippingGateway
<--(620 cents, "EUR") or NoService-- | converts kg to grams, reads rc and amt
v
connection: quote(1200, "DE", "STD") --> foreign API
In the following program, the foreign API gives an exchange rate as a string of the rate times 10000, with a status field. The gateway gives the program a number.
def foreign_rate(src_ccy, dst_ccy, mode): # an awkward foreign API
return {"status": "OK", "rate_x10000": "10850"} if mode == "MID" else {"status": "ERR"}
class RateGateway:
def eur_to_usd(self):
reply = foreign_rate("EUR", "USD", "MID")
if reply["status"] != "OK":
raise LookupError("no rate")
return int(reply["rate_x10000"]) / 10000
print("1 EUR in USD:", RateGateway().eur_to_usd())
1 EUR in USD: 1.085
Example
Each example file has a foreign quote function of a shipping service. It takes the weight in grams and a string of flags, and it returns a map with a return code and the amount as a string of cents. ShippingGateway gives the program one method, standard_cost, that takes kilograms and a country. It returns the cost in cents and the currency, or it raises a NoService error with the reason. The program asks for a parcel of 1.2 kg, which costs 6.20 EUR, and for a parcel of 31.0 kg, which the service does not take. The last call gives a gateway a connection with canned data, as a test does, and the foreign API is not called.
# The foreign API of a shipping service. Its names and types do not fit our code:
# the weight is in grams, the flags are a string, and the result is a dict
# with a return code and the amount as a string of cents.
def foreign_quote(weight_grams, dest, svc_flags):
print(f" connection: quote(weight_grams={weight_grams}, dest={dest}, svc_flags={svc_flags})")
if weight_grams > 30000:
return {"rc": 17, "msg": "too heavy"}
return {"rc": 0, "amt": str(500 + weight_grams // 100 * 10), "cur": "EUR"}
class NoService(Exception):
pass
class ShippingGateway:
"""Our interface to the shipping service, in the terms of our code."""
def __init__(self, connection):
self.connection = connection # the call to the foreign API; a test can replace it
def standard_cost(self, kilograms, country):
reply = self.connection(round(kilograms * 1000), country, "STD")
if reply["rc"] != 0:
raise NoService(f"code {reply['rc']}: {reply['msg']}")
return int(reply["amt"]), reply["cur"]
def show(gateway, kilograms, country):
try:
cents, currency = gateway.standard_cost(kilograms, country)
print(f"parcel of {kilograms:.1f} kg to {country} costs {cents // 100}.{cents % 100:02d} {currency}")
except NoService as e:
print(f"parcel of {kilograms:.1f} kg to {country}: no service ({e})")
gateway = ShippingGateway(foreign_quote)
show(gateway, 1.2, "DE")
show(gateway, 31.0, "DE")
# A test gives the gateway a connection that returns canned data.
canned = ShippingGateway(lambda g, d, f: {"rc": 0, "amt": "999", "cur": "EUR"})
show(canned, 2.0, "FR")
connection: quote(weight_grams=1200, dest=DE, svc_flags=STD)
parcel of 1.2 kg to DE costs 6.20 EUR
connection: quote(weight_grams=31000, dest=DE, svc_flags=STD)
parcel of 31.0 kg to DE: no service (code 17: too heavy)
parcel of 2.0 kg to FR costs 9.99 EUR
- Verdict: idiom. A gateway is a normal class.
ShippingGatewayturns kilograms into grams, the return code into theNoServiceexception, and the string of cents into an integer. - The connection is a function that the gateway takes in its constructor. The last call gives the gateway a lambda with canned data, as a test does.
import java.util.Map;
public class Main {
// The foreign API of a shipping service. Its names and types do not fit our code:
// the weight is in grams, the flags are a string, and the result is a map
// with a return code and the amount as a string of cents.
interface Connection {
Map<String, String> quote(long weightGrams, String dest, String svcFlags);
}
static Map<String, String> foreignQuote(long weightGrams, String dest, String svcFlags) {
System.out.println(" connection: quote(weight_grams=" + weightGrams + ", dest=" + dest + ", svc_flags=" + svcFlags + ")");
if (weightGrams > 30000) return Map.of("rc", "17", "msg", "too heavy");
return Map.of("rc", "0", "amt", String.valueOf(500 + weightGrams / 100 * 10), "cur", "EUR");
}
static class NoService extends Exception {
NoService(String message) { super(message); }
}
record Cost(long cents, String currency) {}
// Our interface to the shipping service, in the terms of our code.
static class ShippingGateway {
private final Connection connection; // the call to the foreign API; a test can replace it
ShippingGateway(Connection connection) { this.connection = connection; }
Cost standardCost(double kilograms, String country) throws NoService {
Map<String, String> reply = connection.quote(Math.round(kilograms * 1000), country, "STD");
if (!reply.get("rc").equals("0")) throw new NoService("code " + reply.get("rc") + ": " + reply.get("msg"));
return new Cost(Long.parseLong(reply.get("amt")), reply.get("cur"));
}
}
static void show(ShippingGateway gateway, double kilograms, String country) {
String kg = String.format("%.1f", kilograms);
try {
Cost c = gateway.standardCost(kilograms, country);
System.out.printf("parcel of %s kg to %s costs %d.%02d %s%n", kg, country, c.cents() / 100, c.cents() % 100, c.currency());
} catch (NoService e) {
System.out.println("parcel of " + kg + " kg to " + country + ": no service (" + e.getMessage() + ")");
}
}
public static void main(String[] args) {
ShippingGateway gateway = new ShippingGateway(Main::foreignQuote);
show(gateway, 1.2, "DE");
show(gateway, 31.0, "DE");
// A test gives the gateway a connection that returns canned data.
ShippingGateway canned = new ShippingGateway((g, d, f) -> Map.of("rc", "0", "amt", "999", "cur", "EUR"));
show(canned, 2.0, "FR");
}
}
connection: quote(weight_grams=1200, dest=DE, svc_flags=STD)
parcel of 1.2 kg to DE costs 6.20 EUR
connection: quote(weight_grams=31000, dest=DE, svc_flags=STD)
parcel of 31.0 kg to DE: no service (code 17: too heavy)
parcel of 2.0 kg to FR costs 9.99 EUR
- Verdict: idiom. The
Connectioninterface is the call to the foreign API, so a method reference or a lambda can be the connection. The gateway returns aCostrecord (Java 16 or later) and throws the checked exceptionNoService.
// The foreign API of a shipping service. Its names and types do not fit our code:
// the weight is in grams, the flags are a string, and the result is an object
// with a return code and the amount as a string of cents.
function foreignQuote(weightGrams, dest, svcFlags) {
console.log(` connection: quote(weight_grams=${weightGrams}, dest=${dest}, svc_flags=${svcFlags})`);
if (weightGrams > 30000) return { rc: 17, msg: "too heavy" };
return { rc: 0, amt: String(500 + Math.floor(weightGrams / 100) * 10), cur: "EUR" };
}
class NoService extends Error {}
// Our interface to the shipping service, in the terms of our code.
class ShippingGateway {
constructor(connection) {
this.connection = connection; // the call to the foreign API; a test can replace it
}
standardCost(kilograms, country) {
const reply = this.connection(Math.round(kilograms * 1000), country, "STD");
if (reply.rc !== 0) throw new NoService(`code ${reply.rc}: ${reply.msg}`);
return { cents: Number(reply.amt), currency: reply.cur };
}
}
function show(gateway, kilograms, country) {
const kg = kilograms.toFixed(1);
try {
const { cents, currency } = gateway.standardCost(kilograms, country);
const amount = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
console.log(`parcel of ${kg} kg to ${country} costs ${amount} ${currency}`);
} catch (e) {
if (!(e instanceof NoService)) throw e;
console.log(`parcel of ${kg} kg to ${country}: no service (${e.message})`);
}
}
const gateway = new ShippingGateway(foreignQuote);
show(gateway, 1.2, "DE");
show(gateway, 31.0, "DE");
// A test gives the gateway a connection that returns canned data.
const canned = new ShippingGateway(() => ({ rc: 0, amt: "999", cur: "EUR" }));
show(canned, 2.0, "FR");
connection: quote(weight_grams=1200, dest=DE, svc_flags=STD)
parcel of 1.2 kg to DE costs 6.20 EUR
connection: quote(weight_grams=31000, dest=DE, svc_flags=STD)
parcel of 31.0 kg to DE: no service (code 17: too heavy)
parcel of 2.0 kg to FR costs 9.99 EUR
- Verdict: idiom. A class with one method is the gateway, and the connection is a function.
NoServiceextendsError, soshowcan tell it apart from other errors. toFixed(1)prints the weight with one decimal, as the other examples do.
package main
import (
"fmt"
"math"
"strconv"
)
// foreignQuote is the foreign API of a shipping service. Its names and types do not
// fit our code: the weight is in grams, the flags are a string, and the result is a
// map with a return code and the amount as a string of cents.
func foreignQuote(weightGrams int, dest, svcFlags string) map[string]string {
fmt.Printf(" connection: quote(weight_grams=%d, dest=%s, svc_flags=%s)\n", weightGrams, dest, svcFlags)
if weightGrams > 30000 {
return map[string]string{"rc": "17", "msg": "too heavy"}
}
return map[string]string{"rc": "0", "amt": strconv.Itoa(500 + weightGrams/100*10), "cur": "EUR"}
}
// connection is the call to the foreign API; a test can replace it.
type connection func(weightGrams int, dest, svcFlags string) map[string]string
// ShippingGateway is our interface to the shipping service, in the terms of our code.
type ShippingGateway struct {
conn connection
}
// NoService is the error for a parcel that the service does not take.
type NoService struct{ code, msg string }
func (e NoService) Error() string { return "code " + e.code + ": " + e.msg }
func (g ShippingGateway) StandardCost(kilograms float64, country string) (int, string, error) {
reply := g.conn(int(math.Round(kilograms*1000)), country, "STD")
if reply["rc"] != "0" {
return 0, "", NoService{reply["rc"], reply["msg"]}
}
cents, err := strconv.Atoi(reply["amt"])
if err != nil {
return 0, "", err
}
return cents, reply["cur"], nil
}
func show(g ShippingGateway, kilograms float64, country string) {
cents, currency, err := g.StandardCost(kilograms, country)
if err != nil {
fmt.Printf("parcel of %.1f kg to %s: no service (%v)\n", kilograms, country, err)
return
}
fmt.Printf("parcel of %.1f kg to %s costs %d.%02d %s\n", kilograms, country, cents/100, cents%100, currency)
}
func main() {
gateway := ShippingGateway{foreignQuote}
show(gateway, 1.2, "DE")
show(gateway, 31.0, "DE")
// A test gives the gateway a connection that returns canned data.
canned := ShippingGateway{func(int, string, string) map[string]string {
return map[string]string{"rc": "0", "amt": "999", "cur": "EUR"}
}}
show(canned, 2.0, "FR")
}
connection: quote(weight_grams=1200, dest=DE, svc_flags=STD)
parcel of 1.2 kg to DE costs 6.20 EUR
connection: quote(weight_grams=31000, dest=DE, svc_flags=STD)
parcel of 31.0 kg to DE: no service (code 17: too heavy)
parcel of 2.0 kg to FR costs 9.99 EUR
- Verdict: idiom. The connection is a function type, and the gateway returns the cost and an error.
NoServiceis an error type, so the caller can test for it witherrors.As. strconv.Atoichecks the string of cents, and the gateway returns its error.
use std::collections::HashMap;
// The foreign API of a shipping service. Its names and types do not fit our code:
// the weight is in grams, the flags are a string, and the result is a map
// with a return code and the amount as a string of cents.
fn foreign_quote(weight_grams: u64, dest: &str, svc_flags: &str) -> HashMap<&'static str, String> {
println!(" connection: quote(weight_grams={}, dest={}, svc_flags={})", weight_grams, dest, svc_flags);
let mut r = HashMap::new();
if weight_grams > 30000 {
r.insert("rc", "17".to_string());
r.insert("msg", "too heavy".to_string());
} else {
r.insert("rc", "0".to_string());
r.insert("amt", (500 + weight_grams / 100 * 10).to_string());
r.insert("cur", "EUR".to_string());
}
r
}
type Connection = Box<dyn Fn(u64, &str, &str) -> HashMap<&'static str, String>>;
// Our interface to the shipping service, in the terms of our code.
struct ShippingGateway {
connection: Connection, // the call to the foreign API; a test can replace it
}
impl ShippingGateway {
// Returns the cost in cents and the currency, or the reason for no service.
fn standard_cost(&self, kilograms: f64, country: &str) -> Result<(u64, String), String> {
let reply = (self.connection)((kilograms * 1000.0).round() as u64, country, "STD");
if reply["rc"] != "0" {
return Err(format!("code {}: {}", reply["rc"], reply["msg"]));
}
let cents = reply["amt"].parse::<u64>().map_err(|e| e.to_string())?;
Ok((cents, reply["cur"].clone()))
}
}
fn show(gateway: &ShippingGateway, kilograms: f64, country: &str) {
match gateway.standard_cost(kilograms, country) {
Ok((cents, currency)) => println!(
"parcel of {:.1} kg to {} costs {}.{:02} {}",
kilograms, country, cents / 100, cents % 100, currency
),
Err(e) => println!("parcel of {:.1} kg to {}: no service ({})", kilograms, country, e),
}
}
fn main() {
let gateway = ShippingGateway { connection: Box::new(foreign_quote) };
show(&gateway, 1.2, "DE");
show(&gateway, 31.0, "DE");
// A test gives the gateway a connection that returns canned data.
let canned = ShippingGateway {
connection: Box::new(|_, _, _| {
let mut r = HashMap::new();
r.insert("rc", "0".to_string());
r.insert("amt", "999".to_string());
r.insert("cur", "EUR".to_string());
r
}),
};
show(&canned, 2.0, "FR");
}
connection: quote(weight_grams=1200, dest=DE, svc_flags=STD)
parcel of 1.2 kg to DE costs 6.20 EUR
connection: quote(weight_grams=31000, dest=DE, svc_flags=STD)
parcel of 31.0 kg to DE: no service (code 17: too heavy)
parcel of 2.0 kg to FR costs 9.99 EUR
- Verdict: idiom. The connection is a boxed closure, so the program can give a different connection to each gateway.
standard_costreturns aResult, with the reason as the error. - The
?operator returns the error ofparseif the amount is not a number.
Consequences
Benefits.
- One place knows the foreign API. A change of the external system, or a move to a different system, changes only the gateway.
- Simpler callers. The callers use the names and types of the program and do not convert units or read return codes.
- Easy tests. A test replaces the connection or the whole gateway with a Test double, with no slow or unavailable external system.
Liabilities.
Without a gateway, the callers convert the data in different ways. In the following program, two parts of the program call the foreign API directly. The invoice forgets that the amount is in cents.
This code runs but gives a wrong answer on purpose.
def foreign_quote(weight_grams, dest, svc_flags): # amt is a string of cents
return {"rc": 0, "amt": "1250", "cur": "EUR"}
# Two parts of the program call the foreign API directly.
checkout = foreign_quote(2500, "DE", "STD")
print("shipping on the checkout page:", int(checkout["amt"]) / 100, checkout["cur"])
invoice = foreign_quote(2500, "DE", "STD")
print("shipping on the invoice:", invoice["amt"], invoice["cur"]) # forgets the cents
shipping on the checkout page: 12.5 EUR
shipping on the invoice: 1250 EUR
Put the call and the conversion into one gateway method, and let both parts of the program call it.
One more layer. A gateway adds a class for each external system. For an API that already fits the program, the gateway can be just the connection.2
A gateway that grows logic. Business rules that use the external data belong in the clients of the gateway, not in the gateway.2
When not to use it
When the foreign vocabulary is the vocabulary of the program. Fowler gives the collection classes of a language as an example of what not to wrap, because "their vocabulary is part of the vocabulary of my software."2
When the program uses the external system in only one place. The code in that place is already the only code that knows the API. A gateway helps when a second caller or a test needs it.
Variants and related patterns
Database gateways. Table Data Gateway has one object for all the rows of a table, and Row Data Gateway has one object for each row.3
Gateway behind a separated interface. The interface of the gateway can be in the package of its clients, and the implementation in another package. The catalog says that "The Separated Interface provides a good plug point for Gateway".4 See Separated interface. During tests, a Service stub can replace the gateway.
Adapter, facade and mediator. Fowler compares the gateway with these three patterns.2 An Adapter pattern fits a class to an interface that already exists, while the interface of a gateway is made when the gateway is written. A Facade pattern is usually written by the writer of the service for all its clients, while a gateway "is written by the client for its particular use."2 A Mediator pattern connects many objects, while a gateway wraps one resource.
Anticorruption layer. In domain-driven design, a gateway is a way to build an anticorruption-layer between two bounded contexts.2
Known uses
- The data source patterns of the book, Table Data Gateway and Row Data Gateway, are gateways to database tables.3
- Fowler notes that the pattern is common but that "there is no widely-used name for it", and that gateways are often called adapters.2
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Gateway, pattern summary
- Martin Fowler, Gateway, 2021, How it Works; When to Use It; Further Reading
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Source Architectural Patterns; Chapter 18, Base Patterns, Gateway
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Separated Interface, pattern summary
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 1V1311 Edit this page History Report an error Markdown