Wrap every vendor
Every third-party library sits behind a small interface of your own, and its types never get past it. Swapping vendors becomes a one-module change.
Every third-party library I use lives behind an interface I wrote. The library gets called from one module, its return values get turned into my own Nouns right there, and nothing else in the program ever knows it exists.
That’s what people mean by an adapter. It sounds like extra work, and it’s a little extra work up front. It pays for itself the first time anything about that vendor changes.
What goes wrong without it
Say gigbook stores songs in Amazon S3, and the S3 library (boto3) gets called wherever it’s convenient:
# setlists/build.py
import json
import boto3
s3 = boto3.client("s3")
def build_setlist(name: str, song_ids: list[str]) -> list[dict]:
songs = []
for song_id in song_ids:
response = s3.get_object(Bucket="gigbook-songs", Key=f"songs/{song_id}.json")
songs.append(json.loads(response["Body"].read()))
return songs
Now the setlist code knows the bucket name, the key format, that songs are JSON, and what boto3’s responses look like. Multiply that by every feature that reads a song. Then one day you want to move to a different storage provider, or just keep songs on disk for offline use, and you’re rewriting every feature. That’s vendor lock-in, and you did it to yourself. (And notice what comes back: a raw dict, not a Song. The vendor’s shape has leaked into the program’s core.)
The adapter
First, an interface that says what the program needs, in the program’s own words. It doesn’t mention S3, buckets, or JSON:
from typing import Protocol
from gigbook.nouns import Song, SongId
class SongNotFoundError(Exception):
def __init__(self, song_id: SongId) -> None:
super().__init__(f"No song is saved with the id {song_id}.")
self.song_id = song_id
class SongStorage(Protocol):
def load_song(self, song_id: SongId) -> Song:
"""Raises SongNotFoundError when no song has this id."""
...
def save_song(self, song: Song) -> None: ...
(A Protocol is Python’s version of an interface: any class with these methods counts as a SongStorage, and the type checker holds it to the exact signatures.)
Then one implementation, which is the only place in the whole app that imports boto3:
import boto3
from botocore.exceptions import ClientError
from gigbook.nouns import Song, SongId
from gigbook.storage._song_serialization import deserialize_song, serialize_song
from gigbook.storage._song_storage import SongNotFoundError
MISSING_OBJECT_ERROR_CODE = "NoSuchKey"
SONG_CONTENT_TYPE = "application/json"
class S3SongStorage:
"""Keeps each song as one JSON object in an S3 bucket.
This file is the only place in the app that knows S3 exists.
"""
def __init__(self, bucket_name: str) -> None:
self._bucket_name = bucket_name
self._client = boto3.client("s3")
def load_song(self, song_id: SongId) -> Song:
try:
response = self._client.get_object(
Bucket=self._bucket_name, Key=_to_object_key(song_id)
)
except ClientError as error:
if error.response.get("Error", {}).get("Code") == MISSING_OBJECT_ERROR_CODE:
raise SongNotFoundError(song_id) from error
raise
return deserialize_song(response["Body"].read())
def save_song(self, song: Song) -> None:
self._client.put_object(
Body=serialize_song(song),
Bucket=self._bucket_name,
ContentType=SONG_CONTENT_TYPE,
Key=_to_object_key(song.song_id),
)
def _to_object_key(song_id: SongId) -> str:
return f"songs/{song_id}.json"
Look at what crosses the boundary: a SongId goes in, a Song comes out. Even the vendor’s error gets translated. boto3 says “missing key” with a ClientError and an error code string, and the rest of the program just sees a SongNotFoundError. Anything else boto3 throws keeps propagating, untouched, so a real failure is never disguised as “not found.”
Now switching to local files for offline use means writing a FileSongStorage with the same two methods and changing one line where the app is wired together. No feature changes. No feature even notices.
The module can be bigger than one file
“Wrap the vendor in one place” doesn’t mean “cram it into one file.” The storage package above is several internal files (the interface, the S3 implementation, serialization), split however reads best. Inside the package, the vendor’s objects are fair game. The rule is only that the package’s public interface speaks the program’s Nouns, and that nothing outside imports its internal files. More on that in Cohesion, coupling, and changing one thing in one place.
Web services: one service layer
Every outside call over the network gets the same treatment. Nothing outside the service layer touches a URL, a header, a status code, or a JSON shape. Callers ask a high-level question and get a Noun back:
import logging
import httpx
from gigbook.chord_charts._chord_chart_service import ChordChartUnavailableError
from gigbook.nouns import ChordChart, ChordSymbol, Song
REQUEST_TIMEOUT_SECONDS = 10.0
logger = logging.getLogger(__name__)
class HttpChordChartService:
"""Talks to the chord chart API. URLs, headers, and JSON never leave this file."""
def __init__(self, base_url: str) -> None:
self._client = httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SECONDS)
def find_chord_chart(self, song: Song) -> ChordChart:
try:
response = self._client.get(f"/charts/{song.song_id}")
response.raise_for_status()
except httpx.HTTPError as error:
logger.warning("Chord chart request failed for %s: %s", song.song_id, error)
raise ChordChartUnavailableError() from error
return ChordChart(
chords=tuple(ChordSymbol(str(chord)) for chord in response.json()["chords"]),
song_id=song.song_id,
)
def close(self) -> None:
"""Closes the connection pool. The AppContext calls this when the app shuts down."""
self._client.close()
The raw error goes to the log, where it’s useful. The caller gets a ChordChartUnavailableError, which it can actually handle, and nobody using the app ever sees an HTTP library’s error text.
Even the environment is a vendor
This applies to more than libraries. Environment variables are an outside system too, so no file calls os.getenv directly. There’s a Config interface that declares every setting the app reads:
class Config(Protocol):
"""Every setting the app reads, and nothing else."""
@property
def chord_chart_api_url(self) -> str: ...
@property
def song_bucket_name(self) -> str: ...
and one implementation that’s the only code allowed to touch the environment. It reads and checks everything once, at startup, and fails right away if anything’s missing:
class EnvironmentConfig:
"""The one place that reads environment variables.
Everything is read and checked here, once, when the app starts, so a
missing variable stops the app immediately instead of an hour later in
the middle of a gig.
"""
def __init__(self, environment: Mapping[str, str] = os.environ) -> None:
self._chord_chart_api_url = _require(environment, CHORD_CHART_API_URL_VARIABLE)
self._song_bucket_name = _require(environment, SONG_BUCKET_NAME_VARIABLE)
@property
def chord_chart_api_url(self) -> str:
return self._chord_chart_api_url
@property
def song_bucket_name(self) -> str:
return self._song_bucket_name
def _require(environment: Mapping[str, str], variable_name: str) -> str:
value = environment.get(variable_name, "").strip()
if not value:
raise MissingConfigurationError(variable_name)
return value
Moving settings into a file, a secrets manager, or command-line flags later is a new Config implementation. Nothing else changes.
The smell test
If I search a codebase for a vendor’s import and it shows up in a lot of files, something’s wrong. It should show up in one module. And this is a rule I don’t just trust myself to follow: the next note shows how to make the build fail if anything else imports it.