AlgoViz

Adapter pattern

easy 50 min

The 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 PaymentGatewayPennyPayLegacyBank
Amount: whole minor unitsSameText with a decimal point
Currency: upper caseLower caseUpper case
Refused: Declinedstatus "declined"code 51
No answer: OutcomeUnknownTimeoutErrorcode 91
Same key, same chargeBuilt inOnly a search by reference
Unknown answerA new status textA new code
Both vendors are invented for this page. The differences are typical.

One checkout, two vendors

Checkout+ pay(order)«interface»PaymentGateway+ charge(money, key)Declined, OutcomeUnknown(our two errors)

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.

1 of 4

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