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.

Video lesson · Chapter 1 of 5

One client, two languages

0:00 / 4:39

See it run

Follow one call across the border: what goes in, what comes out, and what is translated.

Operations

Media player

Three formats, one call. The player never learns who plays.

Step 1 of 8

Wired

playerAudioPlayernownothingoursMp3PlayervlcVlcAdaptermp4Mp4AdapterengineVlcEngineplayingnothingdecoderMp4Decoderfilenonems0

The player holds three objects of the same type. One is native, two are adapters.

Step 1: Wired

class AudioPlayer:    def open(self, file_name, start=0):        player = self._players.get(extension(file_name))        if player is None:            raise PlaybackError("no player")        return player.play(file_name, start)class Mp4Adapter(MediaPlayer):    def play(self, file_name, start=0):        code = self._decoder.load(file_name)        if code != 0:            raise PlaybackError(file_name)        self._decoder.seek(start * 1000)        return self._decoder.run()class VlcAdapter(MediaPlayer):    def play(self, file_name, start=0):        return self._engine.play_vlc(file_name, start * 1000)
Watch
The middle column
Result
Units, order, errors

Read the two pills: seconds on the left side of an adapter, milliseconds on the right.

In the real world

The same adapter pattern doing real jobs. Pick one and step through it.

The same four tests for the fake and for the adapter.

Step 1 of 3

The fake

Memory fakeFirst adapterFixed adapter
Round tripok
Missing keyok
a and A differok
Empty textok

The in-memory version keeps all four promises. Business tests use it.

Step 1: The fake

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Copying the vendor's interface

    major

    The target is the vendor in disguise, so the next vendor does not fit.

    Wrong
    class SmsSender(ABC):    def send_sms(self, number, raw, flags): ...
    Right
    class Notifier(ABC):    def send(self, person, message): ...
  • Ignoring the answer

    critical

    A refused file plays the previous one.

    Wrong
    self._decoder.load(name)return self._decoder.run()
    Right
    if self._decoder.load(name) != 0:    raise PlaybackError(name)return self._decoder.run()
  • Timeout reported as no

    critical

    The money may have moved. The customer pays twice.

    Wrong
    except TimeoutError:    raise Declined(key)
    Right
    except TimeoutError as e:    raise OutcomeUnknown(key) from e
  • A foreign type escapes

    major

    Every caller now depends on the vendor's SDK.

    Wrong
    def charge(self, money, key):    return self._sdk.create_charge(...)
    Right
    def charge(self, money, key):    reply = self._sdk.create_charge(...)    return Receipt("pennypay", reply["id"])
  • Business rules inside

    major

    The second vendor's adapter will not have the discount.

    Wrong
    def charge(self, money, key):    if money.minor > 5000:        money = with_discount(money)
    Right
    def charge(self, money, key):    # translate only    return self._send(money, key)
  • One call per item

    major

    100 network calls where one would do.

    Wrong
    return [self._api.get(i) for i in ids]
    Right
    return self._api.get_many(ids)

Interview tips

  • Start at the client

    • Write the call you wish for.
    • Name it in your words.
    • Keep it small.
  • Make the gap list

    • Names, order, units.
    • Types, errors, empty.
    • One test per row.
  • Refuse in your words

    • No is an answer.
    • Silence is unknown.
    • Keep the cause.
  • Stay thin

    • No rules, no retries.
    • No foreign types out.
    • One adaptee each.
  • Prove it

    • Recording fake.
    • Contract suite.
    • Nightly, live.