Adapter Pattern
Your code rarely talks only to itself. A checkout calls a payment provider, a notification service calls an SMS gateway, a map feature calls a geocoding API. Each of those was written by someone else, with their own method names, units and error styles, and none of them match each other or your design.
The Adapter pattern puts a small translator between your code and the outside API. Your code talks to an interface you designed; the adapter turns those calls into whatever the other side expects.
🔌 In one sentence: wrap a class whose interface doesn't fit in a small class that implements the interface your code expects, translating calls, data and errors in both directions.
The Problem It Solves
Here is a checkout that started with one payment provider, written directly against its SDK. Call it "PayFast": it takes amounts in dollars as strings and raises its own exception type.
from payfast_sdk import PayFastClient, PayFastDeclined
class Checkout:
def __init__(self, payfast: PayFastClient) -> None:
self.payfast = payfast
def pay(self, order: Order) -> bool:
try:
resp = self.payfast.create_charge(
amount=f"{order.total_cents / 100:.2f}", # "12.50"
currency=order.currency.upper(),
card_token=order.card_token,
)
order.payment_ref = resp["charge_id"]
return resp["status"] == "succeeded"
except PayFastDeclined:
return False
Then the business adds a second provider, "CoinPay", for some countries. Its SDK takes integer cents, a
merchant_id, returns an object instead of a dict and signals a decline with a status code instead of an
exception. The natural next step looks like this:
def pay(self, order: Order) -> bool:
if order.country in ("US", "CA"):
... # the PayFast code above
else:
result = self.coinpay.submit_payment(self.merchant_id, order.total_cents, order.card_token)
order.payment_ref = result.txn_id
return result.code == 0
This is where it hurts.
The vendor leaks everywhere. Dollar strings, charge_id, PayFastDeclined and result.code == 0 are
facts about someone else's API, and they now live inside your business logic. Refunds, receipts and the
reconciliation job each grow their own copy of the same translation.
Every new provider edits Checkout. A third provider means another branch in pay, and in refund, and in
every other method that touches payments.
It can't be tested without the SDK. To test "a declined payment leaves the order unpaid", you need a real PayFast client or a mock of its exact method names and response format.
Upgrades break your code. When PayFast ships v3 and renames create_charge, you hunt through every class
that calls it.
⚠️ The smell to look for: imports of a third-party SDK in your domain classes, or vendor-specific field names (
charge_id,txn_id) and error types mixed into business rules. That is the cue for an adapter.