Adapter – how to get along with code that speaks another language
Adapter translates the interface of a foreign class into the interface your code expects. An example of integrating a third-party geocoding SDK in C#, TypeScript, Java, Go and Python.
A library does exactly what you need, but its API fits your code like a US plug fits a European socket. Adapter is a small intermediary class that accepts calls in your format and translates them into the format of the foreign code – so neither side has to change.
The problem: an SDK that thinks in micro-degrees
The pierogi place's delivery module plans courier routes, so it needs coordinates for customer addresses. We picked an external service, GeoNexus. Its SDK works, but it has its own habits: it returns latitude and longitude as integers in micro-degrees, signals errors with status codes instead of exceptions, and in its JavaScript version uses callbacks instead of promises. The first version looked like this:
class RoutePlanner {
plan(order: Order): void {
sdk.lookup(order.address, "PL", (r) => {
if (r.status !== 200) return this.fail(order);
const lat = r.latE6 / 1_000_000; // GeoNexus details leak into the domain
const lng = r.lngE6 / 1_000_000;
this.addStop(order, lat, lng);
});
}
}GeoNexus details – units, status codes, calling style – spilled all over the route planning logic. Tests need a fake of the whole SDK, and when procurement negotiates a cheaper provider, the delivery module will have to be rewritten.
The solution: an interface on our side, a translator in between
First we describe what the delivery module needs in our own words: a Geocoder interface with a single locate(address) method that returns Coordinates in degrees or "not found". Then we write a GeoNexusAdapter that implements this interface and, inside, calls the SDK and translates the result. Route planning knows only Geocoder.
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
| Role | In the example | Responsibility |
|---|---|---|
| Target | Geocoder | the interface the client expects |
| Client | RoutePlanner | uses only the target |
| Adaptee | GeoNexusClient | an existing class with an incompatible API |
| Adapter | GeoNexusAdapter | implements the target, delegates to the adaptee and translates |
The adapter translates much more than method names:
| Aspect | GeoNexus SDK | Our interface |
|---|---|---|
| Units | micro-degrees (50061700) | degrees (50.0617) |
| No result | status 404 | null / Optional.empty() / ErrNotFound |
| Failure | another status | an exception or an error |
| Calling style (JS) | callback | Promise |
| Parameters | query + country code | just the address (the adapter sets the country) |
Implementation in five languages
This is an object adapter: it holds a reference to the SDK client and delegates to it. There is also a class adapter, which inherits from the adaptee and implements the target interface at the same time – it only works where you can inherit from the foreign class and it ties the adapter to one concrete implementation, so in practice composition wins. In Go the adapter does not even declare that it implements Geocoder – having the right method is enough.
GeoNexusAdapter : Geocoder
IGeocoder geocoder = new GeoNexusAdapter(new GeoNexusClient());
var shop = geocoder.Locate("Rynek Główny 1, Kraków");
Console.WriteLine(shop is null ? "not found" : $"{shop.Latitude}, {shop.Longitude}");
// Our port: what the delivery module needs, in our own vocabulary.
public sealed record Coordinates(double Latitude, double Longitude);
public interface IGeocoder
{
Coordinates? Locate(string address);
}
// Third-party SDK (we cannot change it): micro-degrees and status codes.
public sealed record LookupResult(int Status, long LatE6, long LngE6);
public sealed class GeoNexusClient
{
public LookupResult Lookup(string query, string countryCode) => query.Contains("Kraków")
? new LookupResult(200, 50_061_700, 19_937_300)
: new LookupResult(404, 0, 0);
}
// Adapter: implements our interface by translating calls to the SDK.
public sealed class GeoNexusAdapter(GeoNexusClient client) : IGeocoder
{
private const double MicroDegrees = 1_000_000d;
public Coordinates? Locate(string address)
{
var result = client.Lookup(address, countryCode: "PL");
return result.Status switch
{
200 => new Coordinates(result.LatE6 / MicroDegrees, result.LngE6 / MicroDegrees),
404 => null,
_ => throw new InvalidOperationException($"GeoNexus failed with status {result.Status}"),
};
}
}// Our port: what the delivery module needs, in our own vocabulary.
interface Coordinates {
latitude: number;
longitude: number;
}
interface Geocoder {
locate(address: string): Promise<Coordinates | null>;
}
// Third-party SDK (we cannot change it): callbacks, micro-degrees, status codes.
type LookupResult = { status: number; latE6: number; lngE6: number };
class GeoNexusClient {
lookup(query: string, country: string, done: (result: LookupResult) => void): void {
const result = query.includes("Kraków")
? { status: 200, latE6: 50_061_700, lngE6: 19_937_300 }
: { status: 404, latE6: 0, lngE6: 0 };
setTimeout(() => done(result), 10);
}
}
// Adapter: callback -> Promise, micro-degrees -> degrees, status codes -> null or Error.
class GeoNexusAdapter implements Geocoder {
constructor(private readonly client: GeoNexusClient) {}
locate(address: string): Promise<Coordinates | null> {
return new Promise((resolve, reject) => {
this.client.lookup(address, "PL", (r) => {
if (r.status === 200) resolve({ latitude: r.latE6 / 1e6, longitude: r.lngE6 / 1e6 });
else if (r.status === 404) resolve(null);
else reject(new Error(`GeoNexus failed with status ${r.status}`));
});
});
}
}
const geocoder: Geocoder = new GeoNexusAdapter(new GeoNexusClient());
geocoder.locate("Rynek Główny 1, Kraków").then((c) => console.log(c));import java.util.Optional;
// Our port: what the delivery module needs, in our own vocabulary.
record Coordinates(double latitude, double longitude) {}
interface Geocoder {
Optional<Coordinates> locate(String address);
}
// Third-party SDK (we cannot change it): micro-degrees and status codes.
record LookupResult(int status, long latE6, long lngE6) {}
class GeoNexusClient {
LookupResult lookup(String query, String countryCode) {
return query.contains("Kraków")
? new LookupResult(200, 50_061_700, 19_937_300)
: new LookupResult(404, 0, 0);
}
}
// Adapter: implements our interface by translating calls to the SDK.
final class GeoNexusAdapter implements Geocoder {
private static final double MICRO_DEGREES = 1_000_000d;
private final GeoNexusClient client;
GeoNexusAdapter(GeoNexusClient client) { this.client = client; }
@Override
public Optional<Coordinates> locate(String address) {
LookupResult r = client.lookup(address, "PL");
return switch (r.status()) {
case 200 -> Optional.of(new Coordinates(r.latE6() / MICRO_DEGREES, r.lngE6() / MICRO_DEGREES));
case 404 -> Optional.empty();
default -> throw new IllegalStateException("GeoNexus failed with status " + r.status());
};
}
}
public class Delivery {
public static void main(String[] args) {
Geocoder geocoder = new GeoNexusAdapter(new GeoNexusClient());
System.out.println(geocoder.locate("Rynek Główny 1, Kraków"));
}
}package main
import (
"errors"
"fmt"
"strings"
)
// Coordinates and Geocoder are our port, in our own vocabulary.
type Coordinates struct{ Lat, Lng float64 }
var ErrNotFound = errors.New("address not found")
type Geocoder interface {
Locate(address string) (Coordinates, error)
}
// LookupResult and GeoNexusClient come from a third-party SDK we cannot change.
type LookupResult struct {
Status int
LatE6, LngE6 int64
}
type GeoNexusClient struct{}
func (GeoNexusClient) Lookup(query, country string) LookupResult {
if strings.Contains(query, "Kraków") {
return LookupResult{Status: 200, LatE6: 50_061_700, LngE6: 19_937_300}
}
return LookupResult{Status: 404}
}
// GeoNexusAdapter satisfies Geocoder implicitly by translating calls to the SDK.
type GeoNexusAdapter struct{ Client GeoNexusClient }
func (a GeoNexusAdapter) Locate(address string) (Coordinates, error) {
r := a.Client.Lookup(address, "PL")
switch r.Status {
case 200:
return Coordinates{Lat: float64(r.LatE6) / 1e6, Lng: float64(r.LngE6) / 1e6}, nil
case 404:
return Coordinates{}, ErrNotFound
default:
return Coordinates{}, fmt.Errorf("geonexus: unexpected status %d", r.Status)
}
}
func main() {
var g Geocoder = GeoNexusAdapter{Client: GeoNexusClient{}}
c, err := g.Locate("Rynek Główny 1, Kraków")
fmt.Println(c, err)
}from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class Coordinates:
latitude: float
longitude: float
class Geocoder(Protocol):
"""Our port: what the delivery module needs, in our own vocabulary."""
def locate(self, address: str) -> Coordinates | None: ...
class GeoNexusClient:
"""Third-party SDK we cannot change: dicts with micro-degrees and status codes."""
def lookup(self, query: str, country_code: str) -> dict[str, int]:
if "Kraków" in query:
return {"status": 200, "lat_e6": 50_061_700, "lng_e6": 19_937_300}
return {"status": 404}
class GeoNexusAdapter:
"""Implements Geocoder by translating calls to the SDK."""
def __init__(self, client: GeoNexusClient) -> None:
self._client = client
def locate(self, address: str) -> Coordinates | None:
result = self._client.lookup(address, country_code="PL")
match result["status"]:
case 200:
return Coordinates(result["lat_e6"] / 1e6, result["lng_e6"] / 1e6)
case 404:
return None
case status:
raise RuntimeError(f"GeoNexus failed with status {status}")
if __name__ == "__main__":
geocoder: Geocoder = GeoNexusAdapter(GeoNexusClient())
print(geocoder.locate("Rynek Główny 1, Kraków"))Step by step
- Step 1 Describe the client's need – An interface in your domain's language – only the operations and types you actually use.
- Step 2 Write the adapter – A class that implements the interface and holds a reference to the foreign object.
- Step 3 Translate data and errors – Units, date formats, status codes, provider exceptions, calling style.
- Step 4 Keep foreign types inside the adapter – No SDK type appears in the interface signatures or in the domain.
- Step 5 Wire it in the composition root – The DI container or startup code binds the interface to the adapter.
When to use it and when not to
Pros
- integrating foreign code without changing it and without changing your own logic
- provider details enclosed in one place
- switching providers means a new adapter, not rewriting a module
- easy testing with fakes of your own interface
Cons
- another layer of indirection and a few extra types
- an adapter to a very large API becomes large itself
- mirroring the foreign API too literally carries its problems into your domain
Adapter is the natural choice when integrating external libraries, legacy systems, other teams' APIs, and anywhere you want the option to switch providers. It makes no sense when you can simply change both interfaces because you own them – then unify them instead.
Related patterns
Adapter is literally the "adapter" of hexagonal architecture: the application core defines the port, and the adapter plugs the outside world into it. At the level of whole systems, a large adapter is called an anti-corruption layer. Facade hides foreign code too, but it simplifies many classes into one convenient interface instead of fitting one interface to another. Decorator wraps an object without changing its interface, only adding behaviour, and Proxy keeps the same interface and controls access.
Facade – A simple interface to many classes of a subsystem
Decorator – The same interface, additional behaviour
Hexagonal Architecture – Ports and adapters across a whole application
In practice
- .NET –
StreamReaderandStreamWriteradapt a byte stream (Stream) to a text API; packages such asSerilog.Extensions.Loggingadapt third-party logging libraries toILoggerfromMicrosoft.Extensions.Logging. - Java –
InputStreamReaderturns a byte stream into a character stream,Arrays.asList()exposes an array as aList, and in Spring MVCHandlerAdapterlets theDispatcherServletinvoke very different kinds of handlers in one uniform way. - Go –
http.HandlerFuncadapts an ordinary function to thehttp.Handlerinterface;strings.NewReaderandbytes.NewReaderadapt a string and a byte slice toio.Reader. - Python –
io.TextIOWrapperwraps a binary stream and exposes it as a text stream, handling encoding and line endings. - Node.js –
util.promisify()adapts callback-style functions to the world ofPromise– exactly what our TypeScript adapter does.
Quick check
Question: How does Adapter differ from Facade?
- Adapter fits an existing interface to an expected one, Facade simplifies access to many classes
- Adapter always uses inheritance, Facade uses composition
- There is no difference – they are two names for the same pattern
Interview question: object adapter or class adapter?
A class adapter inherits from the adaptee and implements the target interface. It can override the adaptee's behaviour, but it works only with that one class (not its subclasses), requires multiple inheritance or interfaces, and exposes the adaptee's public methods. An object adapter holds a reference and delegates – it works with any implementation of the adaptee, is easy to test and does not couple class hierarchies. The default choice is the object adapter, in line with "composition over inheritance".
Summary
Adapter lets you use foreign code on your own terms: the interface describes your domain's need, and the translation of units, errors and calling style is enclosed in a single class. It is the first structural pattern on the path. The next one – Bridge – shows how to separate two axes of change before the number of classes gets out of hand.