Adapter pattern
easy 50 minThe Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.
Watch lesson4:39
When meanings differ
Two payment vendors behind one interface: money, refusals and lost answers.
The point: a production adapter is judged by what it does with money, refusals and silence. Renaming methods is the smallest part.
The gap list of two vendors
| Promise of PaymentGateway | PennyPay | LegacyBank |
|---|---|---|
| Amount: whole minor units | Same | Text with a decimal point |
| Currency: upper case | Lower case | Upper case |
Refused: Declined | status "declined" | code 51 |
No answer: OutcomeUnknown | TimeoutError | code 91 |
| Same key, same charge | Built in | Only a search by reference |
| Unknown answer | A new status text | A new code |
One checkout, two vendors
1/3Our language
charge(money, key). Two errors, because the caller reacts in two ways: show no, or ask again later.
usesimplementshas (lives on)
Two adapters, one contract
The words of our own program.
from abc import ABC, abstractmethodfrom dataclasses import dataclass@dataclass(frozen=True)class Money: minor: int # cents for EUR, whole yen for JPY currency: str@dataclass(frozen=True)class Receipt: provider: str reference: strclass Declined(Exception): """The answer is no. Trying again changes nothing."""class OutcomeUnknown(Exception): """No answer. The money may have moved or not."""class PaymentGateway(ABC): @abstractmethod def charge(self, money, key): ...Line 7
Whole minor units. A float would lose cents, and a Decimal still would not say how many digits the currency has.
Why it is built this way
- Two errors, because callers do two different things. A third only if they do a third thing.
The answer is lost, the money is not