Adapter
The structural patterns overview introduces Adapter with a short Stripe example. This page goes further. It shows what goes wrong without an adapter, and the difference between class and object adapters. It covers what a good adapter translates beyond method names: units, errors, statuses and idempotency. It also covers how adapters relate to the anti-corruption layer and to ports and adapters, and how to talk about all of this in an interview.
Intent
Convert the interface of an existing class into the interface a client expects, so that classes which couldn't work together because of incompatible interfaces can.
The key word is existing. You write an adapter when both sides already exist and you can't, or shouldn't, change either of them. One side is your code, written against an interface that suits your domain. The other side is a library, an SDK, a legacy module or another team's service, with its own names, types and habits. The adapter sits between them and translates.
An adapter adds no new behaviour that the client would notice. It doesn't cache, it doesn't log for the client's benefit and it doesn't control access. If you find yourself adding those things, you're building a Decorator or a Proxy and should name it that way.
The problem
You're building checkout for an online shop. The business signs up with a payment provider called ZapPay, which ships a Java SDK. A developer integrates it the quickest way possible, straight into the checkout service:
import java.util.*;
// ---- third-party SDK (you can't change this) ----
class ZapPayException extends RuntimeException {
final int code;
ZapPayException(int code, String msg) { super(msg); this.code = code; }
}
class ZapCharge {
final String id; final String state;
ZapCharge(String id, String state) { this.id = id; this.state = state; }
}
class ZapPayClient {
ZapCharge createCharge(Map<String, Object> params) {
if ("tok_declined".equals(params.get("source"))) throw new ZapPayException(402, "card_declined");
return new ZapCharge("zp_1", "succeeded");
}
}
// ---- our code, tangled up with the SDK ----
class CheckoutService {
private final ZapPayClient zap = new ZapPayClient(); // concrete SDK, created inline
String placeOrder(String orderId, double totalDollars, String cardToken) {
Map<String, Object> params = new HashMap<>();
params.put("amount", (long) (totalDollars * 100)); // SDK wants cents
params.put("currency", "usd"); // SDK wants lower case
params.put("source", cardToken);
params.put("idempotency_key", orderId);
try {
ZapCharge charge = zap.createCharge(params);
if (!"succeeded".equals(charge.state)) return "PAYMENT_PENDING";
return "PAID:" + charge.id; // SDK id leaks into our order
} catch (ZapPayException e) {
if (e.code == 402) return "DECLINED"; // SDK error codes leak too
throw e;
}
}
}
class Demo {
public static void main(String[] args) {
CheckoutService checkout = new CheckoutService();
assert checkout.placeOrder("o-1", 12.5, "tok_visa").equals("PAID:zp_1");
assert checkout.placeOrder("o-2", 12.5, "tok_declined").equals("DECLINED");
System.out.println("before: works, but only with ZapPay");
}
}
# ---- third-party SDK (you can't change this) ----
class ZapPayError(Exception):
def __init__(self, code: int, msg: str):
super().__init__(msg)
self.code = code
class ZapPayClient:
def create_charge(self, params: dict) -> dict:
if params["source"] == "tok_declined":
raise ZapPayError(402, "card_declined")
return {"id": "zp_1", "state": "succeeded"}
# ---- our code, tangled up with the SDK ----
class CheckoutService:
def __init__(self):
self.zap = ZapPayClient() # concrete SDK, created inline
def place_order(self, order_id: str, total_dollars: float, card_token: str) -> str:
params = {
"amount": int(total_dollars * 100), # SDK wants cents
"currency": "usd",
"source": card_token,
"idempotency_key": order_id,
}
try:
charge = self.zap.create_charge(params)
except ZapPayError as e:
if e.code == 402: # SDK error codes leak
return "DECLINED"
raise
if charge["state"] != "succeeded":
return "PAYMENT_PENDING"
return "PAID:" + charge["id"]
checkout = CheckoutService()
assert checkout.place_order("o-1", 12.5, "tok_visa") == "PAID:zp_1"
assert checkout.place_order("o-2", 12.5, "tok_declined") == "DECLINED"
print("before: works, but only with ZapPay")
It works, and for a single provider in a small app that might be acceptable. Then three things happen, as they usually do:
- Finance wants a second provider. NimbusPay is cheaper for European cards. Its SDK takes amounts as decimal strings in major units (
"12.50"), never throws on a decline (it returnsok=falsewith an error code instead) and calls a charge a "transaction". The obvious change is anif (provider == ZAP) ... else ...inplaceOrder, and inrefund, and in the reconciliation job, and in the admin tool. - Testing is painful.
CheckoutServiceconstructs the SDK itself, so every unit test either hits the provider's sandbox or needs a mocking library that can interceptnew. - The SDK's vocabulary spreads.
ZapPayException.code == 402, the"succeeded"string, thezp_id format and the "cents aslong" convention now live in checkout. They'll soon live in refunds and reporting too. When ZapPay ships v2 of its SDK and renamescreateCharge, you edit every one of those places.
There's also a quiet bug: (long) (totalDollars * 100) truncates. 0.29 * 100 is 28.999999999999996 in binary floating point, so a 29-cent item is charged 28 cents. The SDK's unit convention pushed a conversion into business code, and the conversion is wrong. (See primitive obsession in Common LLD Mistakes for why money shouldn't be a double at all.)
The root problem is that checkout depends on the shape of a class it doesn't own. The fix is to make checkout depend on an interface shaped for checkout, and to put the translation to each provider's shape in one class per provider.
Structure
classDiagram
class CheckoutService {
-gateway: PaymentGateway
+placeOrder(orderId, total, cardToken) OrderResult
}
class PaymentGateway {
<<interface>>
+charge(amount: Money, cardToken, idempotencyKey) ChargeResult
+refund(chargeId, amount: Money) void
}
class ZapPayAdapter {
-client: ZapPayClient
+charge(amount: Money, cardToken, idempotencyKey) ChargeResult
+refund(chargeId, amount: Money) void
}
class NimbusAdapter {
-sdk: NimbusSdk
+charge(amount: Money, cardToken, idempotencyKey) ChargeResult
+refund(chargeId, amount: Money) void
}
class ZapPayClient {
+createCharge(params) ZapCharge
+createRefund(chargeId, amount) void
}
class NimbusSdk {
+authorizeAndCapture(amount, currency, card, ref) NimbusResponse
+reverse(txnRef, amount) NimbusResponse
}
CheckoutService --> PaymentGateway : uses
PaymentGateway <|.. ZapPayAdapter
PaymentGateway <|.. NimbusAdapter
ZapPayAdapter --> ZapPayClient : delegates to
NimbusAdapter --> NimbusSdk : delegates to
A single charge flows like this:
sequenceDiagram
participant C as CheckoutService
participant A as ZapPayAdapter
participant S as ZapPayClient
C->>A: charge(Money 1250 USD, token, key)
A->>A: build params map, lower-case currency
A->>S: createCharge(params)
S-->>A: ZapCharge(id, state=succeeded)
A->>A: map state to ChargeStatus
A-->>C: ChargeResult(APPROVED, id)
Note over A,S: a 402 from the SDK becomes DECLINED, a 5xx becomes GatewayUnavailable
Participants
| Participant | Role in the example | Responsibility |
|---|---|---|
| Target | PaymentGateway | The interface the client wants, named and typed in the client's language (Money, ChargeResult). |
| Client | CheckoutService | Works only with the target. Knows nothing about any SDK. |
| Adaptee | ZapPayClient, NimbusSdk | The existing class with the useful behaviour and the wrong interface. You don't modify it. |
| Adapter | ZapPayAdapter, NimbusAdapter | Implements the target. Holds (or inherits from) the adaptee and translates every call and every result. |
Who owns the target matters. The target belongs to the client side. If you let the provider's SDK shape the target (a method called createCharge taking a Map), you haven't adapted anything. You've only added a layer of indirection. This is the Dependency Inversion Principle in practice: the high-level module defines the abstraction, and the low-level details conform to it through adapters.
Implementation
The adapters below translate five things, and that list is the real content of a payment adapter:
- Method shape. A params map or positional strings become a typed call.
- Units. Our
Moneyholds minor units (cents) plus a currency code. ZapPay wants minor units with a lower-case currency. Nimbus wants a decimal string in major units, which depends on how many decimal places the currency has (2 for USD, 0 for JPY). - Outcomes. Each SDK reports success, decline and "needs more action" in its own way. The adapter maps them onto one
ChargeStatus. - Errors. Both SDKs have their own exceptions or error codes. A decline is a normal business outcome, so it comes back as a value. An outage is exceptional, so it becomes our own
GatewayUnavailableException. No SDK exception type escapes the adapter. - Idempotency. Our interface takes an idempotency key on every charge. ZapPay supports keys natively. The fake Nimbus SDK takes a "request reference" that serves the same purpose. The adapter maps one onto the other so a retried checkout never charges twice.
The SDK classes at the top of each sample are fakes that stand in for real vendor libraries. They behave like typical payment SDKs but make no network calls.
import java.math.BigDecimal;
import java.util.*;
// ================= third-party SDK #1 (fake, not ours) =================
class ZapPayException extends RuntimeException {
final int code;
ZapPayException(int code, String msg) { super(msg); this.code = code; }
}
class ZapCharge {
final String id; final String state; final long amount;
ZapCharge(String id, String state, long amount) { this.id = id; this.state = state; this.amount = amount; }
}
class ZapPayClient {
private final Map<String, ZapCharge> byKey = new HashMap<>();
final List<String> refunds = new ArrayList<>();
ZapCharge createCharge(Map<String, Object> params) {
String key = (String) params.get("idempotency_key");
if (byKey.containsKey(key)) return byKey.get(key); // replay returns the original
String source = (String) params.get("source");
if (source.equals("tok_outage")) throw new ZapPayException(503, "service unavailable");
if (source.equals("tok_declined")) throw new ZapPayException(402, "card_declined");
String state = source.equals("tok_3ds") ? "requires_action" : "succeeded";
ZapCharge c = new ZapCharge("zp_" + (byKey.size() + 1), state, (Long) params.get("amount"));
byKey.put(key, c);
return c;
}
void createRefund(String chargeId, long amount) { refunds.add(chargeId + ":" + amount); }
}
// ================= third-party SDK #2 (fake, not ours) =================
class NimbusResponse {
final boolean ok; final String txnRef; final String errorCode;
NimbusResponse(boolean ok, String txnRef, String errorCode) { this.ok = ok; this.txnRef = txnRef; this.errorCode = errorCode; }
}
class NimbusSdk {
private final Map<String, String> byRef = new HashMap<>();
final List<String> reversals = new ArrayList<>();
final List<String> amountsSeen = new ArrayList<>();
NimbusResponse authorizeAndCapture(String amountDecimal, String currency, String card, String requestRef) {
amountsSeen.add(amountDecimal + " " + currency);
if (byRef.containsKey(requestRef)) return new NimbusResponse(true, byRef.get(requestRef), null);
if (card.equals("tok_outage")) return new NimbusResponse(false, null, "E_UPSTREAM_TIMEOUT");
if (card.equals("tok_declined")) return new NimbusResponse(false, null, "E_INSUFFICIENT_FUNDS");
String ref = "NB-" + (byRef.size() + 100);
byRef.put(requestRef, ref);
return new NimbusResponse(true, ref, null);
}
NimbusResponse reverse(String txnRef, String amountDecimal) {
reversals.add(txnRef + ":" + amountDecimal);
return new NimbusResponse(true, txnRef, null);
}
}
// ================= our domain: the Target and its types =================
record Money(long minorUnits, String currency) {
Money {
if (minorUnits < 0) throw new IllegalArgumentException("amount must not be negative");
Currency.getInstance(currency); // rejects unknown codes
}
}
enum ChargeStatus { APPROVED, DECLINED, NEEDS_ACTION }
record ChargeResult(ChargeStatus status, String chargeId, String reason) {}
class GatewayUnavailableException extends RuntimeException {
GatewayUnavailableException(String msg, Throwable cause) { super(msg, cause); }
}
interface PaymentGateway {
ChargeResult charge(Money amount, String cardToken, String idempotencyKey);
void refund(String chargeId, Money amount);
}
// ================= Adapter #1: object adapter around ZapPay =================
final class ZapPayAdapter implements PaymentGateway {
private final ZapPayClient client;
ZapPayAdapter(ZapPayClient client) { this.client = client; }
@Override public ChargeResult charge(Money amount, String cardToken, String idempotencyKey) {
Map<String, Object> params = new HashMap<>();
params.put("amount", amount.minorUnits()); // ZapPay also uses minor units
params.put("currency", amount.currency().toLowerCase(Locale.ROOT));
params.put("source", cardToken);
params.put("idempotency_key", idempotencyKey);
try {
ZapCharge c = client.createCharge(params);
return switch (c.state) {
case "succeeded" -> new ChargeResult(ChargeStatus.APPROVED, c.id, null);
case "requires_action" -> new ChargeResult(ChargeStatus.NEEDS_ACTION, c.id, "3-D Secure required");
default -> throw new IllegalStateException("unknown ZapPay state " + c.state);
};
} catch (ZapPayException e) {
if (e.code == 402) return new ChargeResult(ChargeStatus.DECLINED, null, e.getMessage());
throw new GatewayUnavailableException("ZapPay failed with " + e.code, e);
}
}
@Override public void refund(String chargeId, Money amount) {
try {
client.createRefund(chargeId, amount.minorUnits());
} catch (ZapPayException e) {
throw new GatewayUnavailableException("ZapPay refund failed", e);
}
}
}
// ================= Adapter #2: object adapter around Nimbus =================
final class NimbusAdapter implements PaymentGateway {
private static final Set<String> DECLINE_CODES = Set.of("E_INSUFFICIENT_FUNDS", "E_CARD_BLOCKED");
private final NimbusSdk sdk;
NimbusAdapter(NimbusSdk sdk) { this.sdk = sdk; }
static String toDecimal(Money m) { // 1250 USD -> "12.50", 500 JPY -> "500"
int digits = Currency.getInstance(m.currency()).getDefaultFractionDigits();
return BigDecimal.valueOf(m.minorUnits(), digits).toPlainString();
}
@Override public ChargeResult charge(Money amount, String cardToken, String idempotencyKey) {
NimbusResponse r = sdk.authorizeAndCapture(toDecimal(amount), amount.currency(), cardToken, idempotencyKey);
if (r.ok) return new ChargeResult(ChargeStatus.APPROVED, r.txnRef, null);
if (DECLINE_CODES.contains(r.errorCode)) return new ChargeResult(ChargeStatus.DECLINED, null, r.errorCode);
throw new GatewayUnavailableException("Nimbus failed with " + r.errorCode, null);
}
@Override public void refund(String chargeId, Money amount) {
NimbusResponse r = sdk.reverse(chargeId, toDecimal(amount));
if (!r.ok) throw new GatewayUnavailableException("Nimbus reversal failed with " + r.errorCode, null);
}
}
// ================= Client: knows only the Target =================
final class CheckoutService {
private final PaymentGateway gateway;
CheckoutService(PaymentGateway gateway) { this.gateway = gateway; }
String placeOrder(String orderId, Money total, String cardToken) {
ChargeResult r = gateway.charge(total, cardToken, "order-" + orderId);
return switch (r.status()) {
case APPROVED -> "PAID:" + r.chargeId();
case DECLINED -> "DECLINED";
case NEEDS_ACTION -> "AWAITING_CUSTOMER";
};
}
}
class Demo {
public static void main(String[] args) {
ZapPayClient zap = new ZapPayClient();
NimbusSdk nimbus = new NimbusSdk();
CheckoutService viaZap = new CheckoutService(new ZapPayAdapter(zap));
CheckoutService viaNimbus = new CheckoutService(new NimbusAdapter(nimbus));
Money usd = new Money(1250, "USD");
// the same client code works with either provider
assert viaZap.placeOrder("1", usd, "tok_visa").equals("PAID:zp_1");
assert viaNimbus.placeOrder("1", usd, "tok_visa").equals("PAID:NB-100");
// declines come back as values, not SDK exceptions
assert viaZap.placeOrder("2", usd, "tok_declined").equals("DECLINED");
assert viaNimbus.placeOrder("2", usd, "tok_declined").equals("DECLINED");
assert viaZap.placeOrder("3", usd, "tok_3ds").equals("AWAITING_CUSTOMER");
// outages become our own exception type
for (CheckoutService s : List.of(viaZap, viaNimbus)) {
try { s.placeOrder("4", usd, "tok_outage"); assert false; }
catch (GatewayUnavailableException expected) { /* ok */ }
}
// a retried order reuses the idempotency key, so it is not charged twice
assert viaZap.placeOrder("1", usd, "tok_visa").equals("PAID:zp_1");
assert viaNimbus.placeOrder("1", usd, "tok_visa").equals("PAID:NB-100");
// unit translation: Nimbus sees major units with the right number of decimals
new NimbusAdapter(nimbus).charge(new Money(500, "JPY"), "tok_visa", "jp-1");
assert nimbus.amountsSeen.get(0).equals("12.50 USD");
assert nimbus.amountsSeen.contains("500 JPY");
assert NimbusAdapter.toDecimal(new Money(29, "USD")).equals("0.29");
new ZapPayAdapter(zap).refund("zp_1", new Money(250, "USD"));
new NimbusAdapter(nimbus).refund("NB-100", new Money(250, "USD"));
assert zap.refunds.equals(List.of("zp_1:250"));
assert nimbus.reversals.equals(List.of("NB-100:2.50"));
System.out.println("adapter: all checks passed");
}
}
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Protocol
# ================= third-party SDK #1 (fake, not ours) =================
class ZapPayError(Exception):
def __init__(self, code: int, msg: str):
super().__init__(msg)
self.code = code
class ZapPayClient:
def __init__(self):
self._by_key: dict[str, dict] = {}
self.refunds: list[str] = []
def create_charge(self, params: dict) -> dict:
key = params["idempotency_key"]
if key in self._by_key:
return self._by_key[key] # replay returns the original
if params["source"] == "tok_outage":
raise ZapPayError(503, "service unavailable")
if params["source"] == "tok_declined":
raise ZapPayError(402, "card_declined")
state = "requires_action" if params["source"] == "tok_3ds" else "succeeded"
charge = {"id": f"zp_{len(self._by_key) + 1}", "state": state, "amount": params["amount"]}
self._by_key[key] = charge
return charge
def create_refund(self, charge_id: str, amount: int) -> None:
self.refunds.append(f"{charge_id}:{amount}")
# ================= third-party SDK #2 (fake, not ours) =================
@dataclass
class NimbusResponse:
ok: bool
txn_ref: str | None = None
error_code: str | None = None
class NimbusSdk:
def __init__(self):
self._by_ref: dict[str, str] = {}
self.reversals: list[str] = []
self.amounts_seen: list[str] = []
def authorize_and_capture(self, amount: str, currency: str, card: str, request_ref: str) -> NimbusResponse:
self.amounts_seen.append(f"{amount} {currency}")
if request_ref in self._by_ref:
return NimbusResponse(True, self._by_ref[request_ref])
if card == "tok_outage":
return NimbusResponse(False, error_code="E_UPSTREAM_TIMEOUT")
if card == "tok_declined":
return NimbusResponse(False, error_code="E_INSUFFICIENT_FUNDS")
ref = f"NB-{len(self._by_ref) + 100}"
self._by_ref[request_ref] = ref
return NimbusResponse(True, ref)
def reverse(self, txn_ref: str, amount: str) -> NimbusResponse:
self.reversals.append(f"{txn_ref}:{amount}")
return NimbusResponse(True, txn_ref)
# ================= our domain: the Target and its types =================
# A tiny table of minor-unit digits. Use a currency library if you support many currencies.
FRACTION_DIGITS = {"USD": 2, "EUR": 2, "GBP": 2, "JPY": 0}
@dataclass(frozen=True)
class Money:
minor_units: int
currency: str
def __post_init__(self):
if self.minor_units < 0:
raise ValueError("amount must not be negative")
if self.currency not in FRACTION_DIGITS:
raise ValueError(f"unsupported currency {self.currency}")
class ChargeStatus(Enum):
APPROVED = "approved"
DECLINED = "declined"
NEEDS_ACTION = "needs_action"
@dataclass(frozen=True)
class ChargeResult:
status: ChargeStatus
charge_id: str | None = None
reason: str | None = None
class GatewayUnavailable(Exception):
pass
class PaymentGateway(Protocol):
def charge(self, amount: Money, card_token: str, idempotency_key: str) -> ChargeResult: ...
def refund(self, charge_id: str, amount: Money) -> None: ...
# ================= Adapter #1: object adapter around ZapPay =================
class ZapPayAdapter:
def __init__(self, client: ZapPayClient):
self._client = client
def charge(self, amount: Money, card_token: str, idempotency_key: str) -> ChargeResult:
params = {
"amount": amount.minor_units,
"currency": amount.currency.lower(),
"source": card_token,
"idempotency_key": idempotency_key,
}
try:
c = self._client.create_charge(params)
except ZapPayError as e:
if e.code == 402:
return ChargeResult(ChargeStatus.DECLINED, reason=str(e))
raise GatewayUnavailable(f"ZapPay failed with {e.code}") from e
match c["state"]:
case "succeeded":
return ChargeResult(ChargeStatus.APPROVED, c["id"])
case "requires_action":
return ChargeResult(ChargeStatus.NEEDS_ACTION, c["id"], "3-D Secure required")
case other:
raise RuntimeError(f"unknown ZapPay state {other}")
def refund(self, charge_id: str, amount: Money) -> None:
try:
self._client.create_refund(charge_id, amount.minor_units)
except ZapPayError as e:
raise GatewayUnavailable("ZapPay refund failed") from e
# ================= Adapter #2: object adapter around Nimbus =================
class NimbusAdapter:
DECLINE_CODES = {"E_INSUFFICIENT_FUNDS", "E_CARD_BLOCKED"}
def __init__(self, sdk: NimbusSdk):
self._sdk = sdk
@staticmethod
def to_decimal(m: Money) -> str: # 1250 USD -> "12.50", 500 JPY -> "500"
digits = FRACTION_DIGITS[m.currency]
return str(Decimal(m.minor_units).scaleb(-digits))
def charge(self, amount: Money, card_token: str, idempotency_key: str) -> ChargeResult:
r = self._sdk.authorize_and_capture(self.to_decimal(amount), amount.currency, card_token, idempotency_key)
if r.ok:
return ChargeResult(ChargeStatus.APPROVED, r.txn_ref)
if r.error_code in self.DECLINE_CODES:
return ChargeResult(ChargeStatus.DECLINED, reason=r.error_code)
raise GatewayUnavailable(f"Nimbus failed with {r.error_code}")
def refund(self, charge_id: str, amount: Money) -> None:
r = self._sdk.reverse(charge_id, self.to_decimal(amount))
if not r.ok:
raise GatewayUnavailable(f"Nimbus reversal failed with {r.error_code}")
# ================= Client: knows only the Target =================
class CheckoutService:
def __init__(self, gateway: PaymentGateway):
self._gateway = gateway
def place_order(self, order_id: str, total: Money, card_token: str) -> str:
r = self._gateway.charge(total, card_token, f"order-{order_id}")
match r.status:
case ChargeStatus.APPROVED:
return f"PAID:{r.charge_id}"
case ChargeStatus.DECLINED:
return "DECLINED"
case ChargeStatus.NEEDS_ACTION:
return "AWAITING_CUSTOMER"
zap, nimbus = ZapPayClient(), NimbusSdk()
via_zap = CheckoutService(ZapPayAdapter(zap))
via_nimbus = CheckoutService(NimbusAdapter(nimbus))
usd = Money(1250, "USD")
assert via_zap.place_order("1", usd, "tok_visa") == "PAID:zp_1"
assert via_nimbus.place_order("1", usd, "tok_visa") == "PAID:NB-100"
assert via_zap.place_order("2", usd, "tok_declined") == "DECLINED"
assert via_nimbus.place_order("2", usd, "tok_declined") == "DECLINED"
assert via_zap.place_order("3", usd, "tok_3ds") == "AWAITING_CUSTOMER"
for service in (via_zap, via_nimbus):
try:
service.place_order("4", usd, "tok_outage")
raise AssertionError("expected GatewayUnavailable")
except GatewayUnavailable:
pass
assert via_zap.place_order("1", usd, "tok_visa") == "PAID:zp_1" # idempotent replay
assert via_nimbus.place_order("1", usd, "tok_visa") == "PAID:NB-100"
NimbusAdapter(nimbus).charge(Money(500, "JPY"), "tok_visa", "jp-1")
assert nimbus.amounts_seen[0] == "12.50 USD"
assert "500 JPY" in nimbus.amounts_seen
assert NimbusAdapter.to_decimal(Money(29, "USD")) == "0.29"
ZapPayAdapter(zap).refund("zp_1", Money(250, "USD"))
NimbusAdapter(nimbus).refund("NB-100", Money(250, "USD"))
assert zap.refunds == ["zp_1:250"]
assert nimbus.reversals == ["NB-100:2.50"]
print("adapter: all checks passed")
import assert from "node:assert/strict";
// ================= third-party SDK #1 (fake, not ours) =================
class ZapPayError extends Error {
constructor(readonly code: number, message: string) { super(message); }
}
interface ZapCharge { id: string; state: "succeeded" | "requires_action"; amount: number }
class ZapPayClient {
private byKey = new Map<string, ZapCharge>();
readonly refunds: string[] = [];
createCharge(params: { amount: number; currency: string; source: string; idempotency_key: string }): ZapCharge {
const existing = this.byKey.get(params.idempotency_key);
if (existing) return existing; // replay returns the original
if (params.source === "tok_outage") throw new ZapPayError(503, "service unavailable");
if (params.source === "tok_declined") throw new ZapPayError(402, "card_declined");
const state = params.source === "tok_3ds" ? "requires_action" : "succeeded";
const charge: ZapCharge = { id: `zp_${this.byKey.size + 1}`, state, amount: params.amount };
this.byKey.set(params.idempotency_key, charge);
return charge;
}
createRefund(chargeId: string, amount: number): void { this.refunds.push(`${chargeId}:${amount}`); }
}
// ================= third-party SDK #2 (fake, not ours) =================
interface NimbusResponse { ok: boolean; txnRef?: string; errorCode?: string }
class NimbusSdk {
private byRef = new Map<string, string>();
readonly reversals: string[] = [];
readonly amountsSeen: string[] = [];
authorizeAndCapture(amount: string, currency: string, card: string, requestRef: string): NimbusResponse {
this.amountsSeen.push(`${amount} ${currency}`);
const existing = this.byRef.get(requestRef);
if (existing) return { ok: true, txnRef: existing };
if (card === "tok_outage") return { ok: false, errorCode: "E_UPSTREAM_TIMEOUT" };
if (card === "tok_declined") return { ok: false, errorCode: "E_INSUFFICIENT_FUNDS" };
const ref = `NB-${this.byRef.size + 100}`;
this.byRef.set(requestRef, ref);
return { ok: true, txnRef: ref };
}
reverse(txnRef: string, amount: string): NimbusResponse {
this.reversals.push(`${txnRef}:${amount}`);
return { ok: true, txnRef };
}
}
// ================= our domain: the Target and its types =================
// A tiny table of minor-unit digits. Use a currency library if you support many currencies.
const FRACTION_DIGITS: Record<string, number> = { USD: 2, EUR: 2, GBP: 2, JPY: 0 };
class Money {
constructor(readonly minorUnits: number, readonly currency: string) {
if (!Number.isInteger(minorUnits) || minorUnits < 0) throw new RangeError("amount must be a non-negative integer");
if (!(currency in FRACTION_DIGITS)) throw new RangeError(`unsupported currency ${currency}`);
}
}
type ChargeResult =
| { status: "approved"; chargeId: string }
| { status: "declined"; reason: string }
| { status: "needs_action"; chargeId: string; reason: string };
class GatewayUnavailableError extends Error {}
interface PaymentGateway {
charge(amount: Money, cardToken: string, idempotencyKey: string): ChargeResult;
refund(chargeId: string, amount: Money): void;
}
// ================= Adapter #1: object adapter around ZapPay =================
class ZapPayAdapter implements PaymentGateway {
constructor(private readonly client: ZapPayClient) {}
charge(amount: Money, cardToken: string, idempotencyKey: string): ChargeResult {
let c: ZapCharge;
try {
c = this.client.createCharge({
amount: amount.minorUnits,
currency: amount.currency.toLowerCase(),
source: cardToken,
idempotency_key: idempotencyKey,
});
} catch (e) {
if (e instanceof ZapPayError && e.code === 402) return { status: "declined", reason: e.message };
throw new GatewayUnavailableError("ZapPay failed", { cause: e });
}
return c.state === "succeeded"
? { status: "approved", chargeId: c.id }
: { status: "needs_action", chargeId: c.id, reason: "3-D Secure required" };
}
refund(chargeId: string, amount: Money): void {
try {
this.client.createRefund(chargeId, amount.minorUnits);
} catch (e) {
throw new GatewayUnavailableError("ZapPay refund failed", { cause: e });
}
}
}
// ================= Adapter #2: object adapter around Nimbus =================
class NimbusAdapter implements PaymentGateway {
private static readonly DECLINE_CODES = new Set(["E_INSUFFICIENT_FUNDS", "E_CARD_BLOCKED"]);
constructor(private readonly sdk: NimbusSdk) {}
static toDecimal(m: Money): string { // 1250 USD -> "12.50", 500 JPY -> "500"
const digits = FRACTION_DIGITS[m.currency];
if (digits === 0) return String(m.minorUnits);
const s = String(m.minorUnits).padStart(digits + 1, "0"); // integer string maths, no floats
return `${s.slice(0, -digits)}.${s.slice(-digits)}`;
}
charge(amount: Money, cardToken: string, idempotencyKey: string): ChargeResult {
const r = this.sdk.authorizeAndCapture(NimbusAdapter.toDecimal(amount), amount.currency, cardToken, idempotencyKey);
if (r.ok && r.txnRef) return { status: "approved", chargeId: r.txnRef };
if (r.errorCode && NimbusAdapter.DECLINE_CODES.has(r.errorCode)) return { status: "declined", reason: r.errorCode };
throw new GatewayUnavailableError(`Nimbus failed with ${r.errorCode}`);
}
refund(chargeId: string, amount: Money): void {
const r = this.sdk.reverse(chargeId, NimbusAdapter.toDecimal(amount));
if (!r.ok) throw new GatewayUnavailableError(`Nimbus reversal failed with ${r.errorCode}`);
}
}
// ================= Client: knows only the Target =================
class CheckoutService {
constructor(private readonly gateway: PaymentGateway) {}
placeOrder(orderId: string, total: Money, cardToken: string): string {
const r = this.gateway.charge(total, cardToken, `order-${orderId}`);
switch (r.status) {
case "approved": return `PAID:${r.chargeId}`;
case "declined": return "DECLINED";
case "needs_action": return "AWAITING_CUSTOMER";
}
}
}
const zap = new ZapPayClient();
const nimbus = new NimbusSdk();
const viaZap = new CheckoutService(new ZapPayAdapter(zap));
const viaNimbus = new CheckoutService(new NimbusAdapter(nimbus));
const usd = new Money(1250, "USD");
assert.equal(viaZap.placeOrder("1", usd, "tok_visa"), "PAID:zp_1");
assert.equal(viaNimbus.placeOrder("1", usd, "tok_visa"), "PAID:NB-100");
assert.equal(viaZap.placeOrder("2", usd, "tok_declined"), "DECLINED");
assert.equal(viaNimbus.placeOrder("2", usd, "tok_declined"), "DECLINED");
assert.equal(viaZap.placeOrder("3", usd, "tok_3ds"), "AWAITING_CUSTOMER");
for (const service of [viaZap, viaNimbus]) {
assert.throws(() => service.placeOrder("4", usd, "tok_outage"), GatewayUnavailableError);
}
assert.equal(viaZap.placeOrder("1", usd, "tok_visa"), "PAID:zp_1"); // idempotent replay
assert.equal(viaNimbus.placeOrder("1", usd, "tok_visa"), "PAID:NB-100");
new NimbusAdapter(nimbus).charge(new Money(500, "JPY"), "tok_visa", "jp-1");
assert.equal(nimbus.amountsSeen[0], "12.50 USD");
assert.ok(nimbus.amountsSeen.includes("500 JPY"));
assert.equal(NimbusAdapter.toDecimal(new Money(29, "USD")), "0.29");
new ZapPayAdapter(zap).refund("zp_1", new Money(250, "USD"));
new NimbusAdapter(nimbus).refund("NB-100", new Money(250, "USD"));
assert.deepEqual(zap.refunds, ["zp_1:250"]);
assert.deepEqual(nimbus.reversals, ["NB-100:2.50"]);
console.log("adapter: all checks passed");
A few details are worth pointing out because interviewers look for them:
- The adapters are thin, but not trivial. Most of their lines are translation: building a params map, converting units, mapping states and errors. There's no business rule in them. "Should we retry a declined card?" or "is this order allowed?" belong in checkout or the domain, not in an adapter.
- The client never sees a vendor type.
CheckoutServiceimports nothing from either SDK, not even an exception class. That's what lets you swap providers, run both side by side, or route by card region without touching checkout. - Unknown vendor states fail loudly. If ZapPay adds a new
statevalue, the Java and Python adapters throw instead of guessing. Silently treating an unknown state as "approved" in a payment path is how you ship goods you weren't paid for. - The currency conversion uses integer or decimal maths.
BigDecimal.valueOf(minor, scale)in Java,Decimal.scalebin Python and string slicing in TypeScript all avoid binary floating point, so 29 cents stays0.29.
Choosing the adapter at runtime
Once providers sit behind one interface, routing becomes a small, separate decision. You can make it in configuration (one gateway for the whole app), or per request with a tiny router that is itself a PaymentGateway. A router that picks an adapter by currency doesn't need any new pattern. It's a few lines of composition, and checkout still sees one interface. If routing rules grow (by card brand, by cost, by fallback on outage), that router becomes a candidate for Strategy or Chain of Responsibility. The adapters don't change.
Class adapter vs object adapter
There are two ways to build an adapter.
- An object adapter holds an adaptee and delegates to it. Everything above is an object adapter.
- A class adapter inherits from the adaptee and implements the target at the same time. The adapter is an adaptee, with the target's methods added on top.
The example is a sensor library. Your monitoring code expects a TemperatureSensor that reports Celsius. A legacy driver class reads the hardware and reports Fahrenheit, and the driver also has a calibrate() method you'd like to keep using.
interface TemperatureSensor { double celsius(); }
class LegacyThermometer { // the adaptee, from an old driver package
protected double offset = 0;
double readFahrenheit() { return 98.6 + offset; }
void calibrate(double delta) { offset += delta; }
}
// class adapter: IS-A LegacyThermometer, and also a TemperatureSensor
class ThermometerClassAdapter extends LegacyThermometer implements TemperatureSensor {
@Override public double celsius() { return (readFahrenheit() - 32) * 5 / 9; }
}
// object adapter: HAS-A LegacyThermometer (or any subclass of it)
class ThermometerObjectAdapter implements TemperatureSensor {
private final LegacyThermometer legacy;
ThermometerObjectAdapter(LegacyThermometer legacy) { this.legacy = legacy; }
@Override public double celsius() { return (legacy.readFahrenheit() - 32) * 5 / 9; }
}
class Demo {
public static void main(String[] args) {
ThermometerClassAdapter classAdapter = new ThermometerClassAdapter();
classAdapter.calibrate(1.8); // adaptee methods are still visible
assert Math.abs(classAdapter.celsius() - 38.0) < 1e-9;
LegacyThermometer shared = new LegacyThermometer(); // an instance someone else created
TemperatureSensor objectAdapter = new ThermometerObjectAdapter(shared);
assert Math.abs(objectAdapter.celsius() - 37.0) < 1e-9;
shared.calibrate(1.8); // the adapter sees changes to the shared instance
assert Math.abs(objectAdapter.celsius() - 38.0) < 1e-9;
System.out.println("class and object adapters agree");
}
}
from typing import Protocol
class TemperatureSensor(Protocol):
def celsius(self) -> float: ...
class LegacyThermometer: # the adaptee
def __init__(self):
self.offset = 0.0
def read_fahrenheit(self) -> float:
return 98.6 + self.offset
def calibrate(self, delta: float) -> None:
self.offset += delta
class CelsiusMixin:
"""Target behaviour written against the adaptee's method name."""
def celsius(self) -> float:
return (self.read_fahrenheit() - 32) * 5 / 9 # type: ignore[attr-defined]
# class adapter through multiple inheritance
class ThermometerClassAdapter(CelsiusMixin, LegacyThermometer):
pass
# object adapter through composition
class ThermometerObjectAdapter:
def __init__(self, legacy: LegacyThermometer):
self._legacy = legacy
def celsius(self) -> float:
return (self._legacy.read_fahrenheit() - 32) * 5 / 9
def report(sensor: TemperatureSensor) -> str:
return f"{sensor.celsius():.1f} C"
class_adapter = ThermometerClassAdapter()
class_adapter.calibrate(1.8)
assert report(class_adapter) == "38.0 C"
shared = LegacyThermometer()
object_adapter = ThermometerObjectAdapter(shared)
assert report(object_adapter) == "37.0 C"
shared.calibrate(1.8)
assert report(object_adapter) == "38.0 C"
print("class and object adapters agree")
import assert from "node:assert/strict";
interface TemperatureSensor { celsius(): number }
class LegacyThermometer { // the adaptee
protected offset = 0;
readFahrenheit(): number { return 98.6 + this.offset; }
calibrate(delta: number): void { this.offset += delta; }
}
// class adapter: extends the adaptee, implements the target
class ThermometerClassAdapter extends LegacyThermometer implements TemperatureSensor {
celsius(): number { return ((this.readFahrenheit() - 32) * 5) / 9; }
}
// object adapter: wraps any LegacyThermometer
class ThermometerObjectAdapter implements TemperatureSensor {
constructor(private readonly legacy: LegacyThermometer) {}
celsius(): number { return ((this.legacy.readFahrenheit() - 32) * 5) / 9; }
}
const classAdapter = new ThermometerClassAdapter();
classAdapter.calibrate(1.8);
assert.ok(Math.abs(classAdapter.celsius() - 38) < 1e-9);
const shared = new LegacyThermometer();
const objectAdapter: TemperatureSensor = new ThermometerObjectAdapter(shared);
assert.ok(Math.abs(objectAdapter.celsius() - 37) < 1e-9);
shared.calibrate(1.8);
assert.ok(Math.abs(objectAdapter.celsius() - 38) < 1e-9);
console.log("class and object adapters agree");
The two forms trade off like this:
| Class adapter | Object adapter | |
|---|---|---|
| Mechanism | Inheritance from the adaptee | Composition, holds an adaptee reference |
| Works with adaptee subclasses | No, it's bound to one concrete class | Yes, pass in any subclass or a test fake |
| Can wrap an instance someone else created | No, it is the instance | Yes |
| Can override adaptee behaviour | Yes, by overriding methods | Only by wrapping, not overriding |
| Exposes the adaptee's own methods | Yes (calibrate() above), which can be a feature or a leak | Only what you forward |
| Needs | An adaptee that isn't final/sealed, and a language with single inheritance plus interfaces (Java, TS) or multiple inheritance (Python, C++) | Nothing special |
| Number of extra objects | One | Two |
Default to the object adapter. It's looser coupling, it works with final classes (most SDK clients are final or created by factories you don't control), it works with instances handed to you by a framework, and it's easy to test by passing a fake adaptee. The class adapter is worth it in two narrow cases. The first is when you must override a protected hook in the adaptee as part of the adaptation. The second is when callers genuinely need the adaptee's own API on the same object, as with calibrate() above. Note that the second case is also a warning sign: a class adapter leaks every public adaptee method into the target's world, which undermines the isolation you wanted.
In Java and TypeScript a class can extend only one class, so a class adapter can adapt exactly one adaptee. Python's multiple inheritance allows mixing several, but method resolution order then becomes part of your design. That's rarely worth it for an adapter.
Two-way adapters
Sometimes both sides need to talk to each other in their own language. This happens during migrations. The old billing module calls LegacyLedger.post(...), the new one implements Ledger.record(...), and for a few months new code must work with old ledgers and old code with new ledgers.
A two-way adapter implements both interfaces and translates in both directions. It works best when the two interfaces are close in meaning, so that each method has a clean counterpart:
from typing import Protocol
class LegacyLedger(Protocol):
def post(self, account: str, cents: int) -> None: ...
def balance_cents(self, account: str) -> int: ...
class Ledger(Protocol):
def record(self, account: str, amount: str) -> None: ... # "12.50"
def balance(self, account: str) -> str: ...
class NewLedger:
def __init__(self):
self._entries: dict[str, list[int]] = {}
def record(self, account: str, amount: str) -> None:
whole, _, frac = amount.partition(".")
self._entries.setdefault(account, []).append(int(whole) * 100 + int(frac.ljust(2, "0")))
def balance(self, account: str) -> str:
total = sum(self._entries.get(account, []))
return f"{total // 100}.{total % 100:02d}"
class TwoWayLedgerAdapter:
"""Speaks both LegacyLedger and Ledger, backed by a NewLedger."""
def __init__(self, backing: NewLedger):
self._backing = backing
# Ledger side: pass straight through
def record(self, account: str, amount: str) -> None:
self._backing.record(account, amount)
def balance(self, account: str) -> str:
return self._backing.balance(account)
# LegacyLedger side: translate cents to decimal strings and back
def post(self, account: str, cents: int) -> None:
self._backing.record(account, f"{cents // 100}.{cents % 100:02d}")
def balance_cents(self, account: str) -> int:
whole, frac = self.balance(account).split(".")
return int(whole) * 100 + int(frac)
def old_billing_job(ledger: LegacyLedger) -> None:
ledger.post("acme", 1999)
def new_billing_job(ledger: Ledger) -> None:
ledger.record("acme", "0.01")
shared = TwoWayLedgerAdapter(NewLedger())
old_billing_job(shared)
new_billing_job(shared)
assert shared.balance("acme") == "20.00"
assert shared.balance_cents("acme") == 2000
print("both callers see one consistent ledger")
Use two-way adapters sparingly. They are migration scaffolding, and they're easiest to delete when they have a clear removal date. If the two interfaces differ in meaning rather than just syntax (one is transactional and the other isn't, say), a single class pretending to be both will end up lying to one side.
Adapters at the boundary: the anti-corruption layer
The payment adapters above do a small version of what Domain-Driven Design calls an anti-corruption layer. The ACL's job is to stop a foreign model (a vendor's, a legacy system's or another bounded context's) from leaking into yours. It's built mostly from adapters, plus whatever else the translation needs:
- Adapters convert calls and data shapes, as above.
- Translators map whole concepts. The vendor's "transaction" with five statuses becomes your
Paymentwith three, and their "customer" becomes yourAccountHolder. - Facades simplify a sprawling vendor API down to the three operations you use (see Facade).
- Caching or batching sometimes, to protect your service from a slow or rate-limited upstream. That part is Proxy, not Adapter.
So "adapter" is a class-level pattern, and "anti-corruption layer" is an architecture-level boundary made from several patterns. In hexagonal architecture the same idea gets a name of its own. The port is the target interface your application core defines (our PaymentGateway), and adapters plug real technology into it: a ZapPay adapter, a Postgres adapter, an HTTP controller adapter. If you understand the GoF Adapter well, you already understand the mechanics of both.
Testing adapters
Adapters sit exactly on the seam between your code and someone else's, so test them from both sides:
- Client-side tests use a fake target. Checkout tests construct
CheckoutServicewith an in-memoryPaymentGatewaythat returns whatever outcome you need. No SDK, no network, no mocking library. - Adapter tests use a fake or sandbox adaptee. Feed the adapter each vendor response you care about (success, every decline code, timeout, unknown state) and check it produces the right
ChargeResultor exception. The fake SDK classes above are exactly this. - One contract test suite, run against every adapter. Write the expectations of
PaymentGatewayonce ("a decline returns DECLINED", "a replayed key returns the same charge id", "an outage throwsGatewayUnavailable") and run them againstZapPayAdapter,NimbusAdapterand the in-memory fake. If the fake passes the same contract, the client-side tests can trust it.
Real-world uses
Adapters are everywhere in standard libraries, usually without "Adapter" in the name:
java.util.Arrays.asList(array)returns a fixed-sizeListview backed by the array. The array is the adaptee andListis the target. Writes throughsetchange the array, which shows it's a view, not a copy.java.io.InputStreamReaderadapts a byte-orientedInputStreamto the character-orientedReaderinterface, decoding bytes with a charset.OutputStreamWriterdoes the same in the other direction.java.util.Collections.list(Enumeration)andCollections.enumeration(Collection)bridge the pre-CollectionsEnumerationinterface and the modern collection types in both directions.java.util.concurrent.Executors.callable(Runnable, result)turns aRunnableinto aCallableso it can be submitted where aCallableis expected.- Spring MVC's
HandlerAdapter. TheDispatcherServletcan invoke very different kinds of handlers: annotated@RequestMappingmethods,HttpRequestHandlerbeans and old-styleControllerimplementations. It doesn't know how to call each one. Instead it asks each registeredHandlerAdapterwhether itsupportsthe handler, then callshandlethrough the adapter.RequestMappingHandlerAdapteris the one behind annotated controllers. - Python's
io.TextIOWrapperwraps a binary buffered stream and presents a text stream interface, handling encoding and newline translation.open(path, "r")gives you one layered over a binary file. - Python's
functools.cmp_to_keyadapts an old-style two-argument comparison function into the key function thatsortedandlist.sortexpect. - Node's
util.promisifyadapts a function that takes an error-first callback into one that returns a Promise.util.callbackifygoes the other way. - Logging bridges such as SLF4J's
jcl-over-slf4jandjul-to-slf4jlet code written against one logging API send its output through another.
When NOT to use it
When you own both sides. If the "incompatible" class is your own code, change it. An adapter between two of your own classes is usually a sign that one of them has the wrong interface, and the adapter just hides the disagreement. Rename the method or change the type, and delete the indirection.
When there's only one implementation and it's a stable, well-designed library. Wrapping java.time or Python's pathlib in your own DateProvider or FileSystem interface "in case we switch" adds code that every reader has to step through and never pays off. Adapt at the boundaries that are actually volatile: vendors you might replace, APIs with awkward shapes, legacy systems on their way out, and anything you need to fake in tests. Injecting a clock or a filesystem for testability is a fine reason. "Maybe one day" isn't.
When the target simply mirrors the adaptee. A ZapPayGateway interface with a createCharge(Map params) method, implemented by a class that forwards to ZapPayClient.createCharge, adapts nothing. You've doubled the surface and kept all the coupling. If you can't name the translation the adapter performs, you don't need it yet.
When the semantics don't match, not just the syntax. An adapter can rename methods, convert units and map errors. It can't make a fire-and-forget API transactional, make an eventually-consistent store read-your-writes, or make a 2-second call fast. If the adaptee can't honour the target's contract, the adapter will hide that until production. You need a different design (a queue, a saga, a cache), and the adapter is only a small part of it.
When a function will do. In languages with first-class functions, adapting a single method often needs no class at all. util.promisify(fs.readFile), a lambda items.sort(key=cmp_to_key(compare)) or Runnable r = legacy::doWork are all adapters in spirit. Writing a named class for a one-method conversion is ceremony.
The costs, even when it's right: one more type per adaptee, one more hop when debugging, and a translation layer that must be kept current as the vendor's SDK changes. The last one is the real cost. Adapters age as their adaptees do, so pin SDK versions and keep the contract tests running.
Related patterns
| Pattern | Also wraps something? | How it differs from Adapter |
|---|---|---|
| Facade | Yes, a whole subsystem | Facade defines a new, simpler interface over many classes. Adapter conforms to an existing interface the client already expects, usually for one class. Facade is about simplicity, Adapter about compatibility. |
| Decorator | Yes, one object | Decorator keeps the same interface and adds behaviour. It can be stacked. Adapter changes the interface and adds nothing visible. |
| Proxy | Yes, one object | Proxy keeps the same interface and controls access (lazy loading, permissions, remote calls, caching). Adapter changes the interface. |
| Bridge | Holds an implementor | Same object shape (abstraction holds an implementor), different timing and intent. Bridge is designed up front so two hierarchies can vary independently. Adapter is applied after the fact to make existing things fit. |
| Strategy | Holds a delegate | Strategy swaps algorithms behind an interface you designed for that purpose. Several adapters behind one target can look like strategies to the client, and in practice they often are. The difference is why each class exists: an adapter exists to translate a foreign API. |
| Anti-corruption layer | Yes, a whole external model | An architectural boundary built mostly from adapters, translators and facades. |
The quickest way to tell the wrappers apart is to ask two questions. Does the interface change? If yes, it's Adapter (one class) or Facade (a subsystem). If no, it's Decorator or Proxy. What does the wrapper add? Behaviour means Decorator. Control over access means Proxy.
The smell that suggests it
- Vendor types in your domain code. Imports of
com.zappay.*,stripe,boto3or a legacy package in classes that hold business rules. You see their exception classes in yourcatchblocks and their status strings in yourifs. - The same conversion in several places.
(long) (amount * 100),currency.toLowerCase()or "map error code 402 to declined" copied into checkout, refunds and reconciliation. if (provider == X) ... else if (provider == Y) ...spread across several methods, each branch calling a different SDK.- Tests that need the network or a heavyweight mock because a class creates its SDK client with
new. - An upgrade that touches many files. When a library's v2 renames a method and you edit fifteen files, the library's interface has leaked into fifteen places that should have depended on yours.
- Two parts of the codebase that do the same thing through different interfaces, and glue code converting between them in every caller.
The refactoring is mechanical. Write the interface the client wishes it had. Move every call to the foreign API into one class that implements that interface. Inject that class into the client. Then delete the conversions scattered around the callers.
Interview questions
-
"What's the difference between a class adapter and an object adapter, and which would you use?" A class adapter inherits from the adaptee and implements the target. An object adapter holds a reference to the adaptee and delegates. I'd default to the object adapter: it works with final classes and with instances I don't construct, it can wrap any subclass, and it's easy to test with a fake. I'd consider a class adapter only if I needed to override a protected hook in the adaptee.
-
"You're integrating Stripe and a second payment provider. Walk me through the design." I'd define a
PaymentGatewayinterface in our domain's terms:charge(Money, token, idempotencyKey)returning a result type, plusrefund. Then one adapter per provider that converts units, maps statuses, turns declines into result values and outages into our own exception type, and passes through idempotency keys. Checkout depends only on the interface and gets an adapter injected. I'd add a contract test suite that runs against every adapter and against an in-memory fake. -
"Should the adapter throw the vendor's exceptions?" No. If a vendor exception escapes, every caller has to import and catch the vendor type, and the coupling is back. The adapter catches vendor errors and either returns a domain result (for expected outcomes like a decline) or throws a domain exception (for failures like an outage), keeping the original as the cause for debugging.
-
"How is Adapter different from Facade?" Adapter makes one existing class conform to an interface the client already expects, so it's about compatibility. Facade puts a new, simpler interface in front of a whole subsystem, so it's about simplicity. A payment adapter might use a facade internally if the vendor's SDK needs five calls for one charge, but the client sees only the target interface.
-
"And from Decorator and Proxy?" Decorator and Proxy keep the wrapped object's interface unchanged. Decorator adds behaviour, and Proxy controls access. Adapter changes the interface and shouldn't add visible behaviour. If my "adapter" starts caching or retrying, I'd pull that into a separate decorator around it so each class has one job.
-
"Where would you put retry logic for a flaky payment provider?" Not in checkout and preferably not in the adapter's translation code. A retrying decorator (or a resilience library) wrapping the
PaymentGatewaykeeps retries reusable across providers. It must only retry operations that are safe to repeat, which is why the idempotency key is part of the interface: with it, retrying a charge can't double-charge. See circuit breakers for the failure side. -
"Isn't wrapping every library in an adapter over-engineering?" Yes, if you do it everywhere. I adapt the boundaries that are volatile or awkward: external vendors we might switch, legacy APIs, anything with a shape that would spread through the codebase, and dependencies I need to fake in tests. A stable, well-designed standard library doesn't need an interface of my own in front of it.
-
"What is a two-way adapter, and when have you seen one used?" It implements both interfaces and translates in both directions, so old and new code can both use the same object. It's typical during migrations, such as moving from a legacy ledger API to a new one while both kinds of callers still exist. It should be temporary, and it only works if the two interfaces mean the same thing.
-
"How does the Adapter pattern relate to hexagonal architecture?" In hexagonal architecture the application core defines ports, which are interfaces in its own terms. Adapters connect technology to those ports: a database adapter implements a repository port, and a payment adapter implements a gateway port. It's the GoF Adapter used systematically at every boundary, with the dependency always pointing from the adapter towards the core.
-
"Give a JDK example of Adapter."
InputStreamReaderadapts a byteInputStreamto the characterReaderinterface by decoding with a charset.Arrays.asListis another: it presents an array as a fixed-sizeListthat writes through to the array.