Adapter Pattern: Making Incompatible Interfaces Work Together
The Adapter Pattern helps your application work with external APIs, SDKs, and legacy systems without leaking their interfaces into business logic. Learn how to implement adapters in TypeScript, translate provider-specific data and errors, and decide when an adapter creates a useful boundary versus unnecessary abstraction.
Table of Contents
- Introduction
- 1. The Problem: External Interfaces Don't Match Your Application
- 2. The Core Idea Behind the Adapter Pattern
- 3. Implementing Adapter in TypeScript
- 4. Adapting Third-Party APIs and SDKs
- 5. Adapter vs. Decorator, Proxy, and Facade
- 6. Common Adapter Mistakes
- 7. When Should You Use Adapter?
- Summary
Introduction
Integrating an external service often looks straightforward at first.
You install an SDK, create a client, call a method, and process the response. Everything works until the external interface does not match the way your application is designed.
Perhaps your application expects a payment provider to expose a method called charge(), but the SDK provides createPaymentIntent(). One provider returns amounts in cents, another expects decimal currency values, and a third represents payment failures using provider-specific error codes.
You could modify your application to accommodate every provider. But as integrations grow, provider-specific details begin spreading across business logic, tests, and application services.
The result is an application that knows too much about the systems it depends on.
The Adapter Pattern addresses this problem by translating one interface into another interface that the client expects.
Instead of changing the external system or forcing your application to understand every external interface, you introduce a boundary that makes them compatible.
The important question is not simply how to implement an adapter. It is where interface translation belongs, and how much complexity that boundary should absorb.
1. The Problem: External Interfaces Don't Match Your Application
Imagine you are building an application that supports multiple payment providers.
Your application needs only one operation: charge a customer.
A reasonable application-level contract might look like this:
interface PaymentGateway {
charge(input: {
customerId: string;
amount: number;
currency: string;
}): Promise<{
transactionId: string;
status: "succeeded" | "failed";
}>;
}The application can now express its business requirement without committing to a particular payment vendor.
However, an external provider might expose a different interface:
interface AcmePayClient {
createPaymentIntent(input: {
customer: string;
amountInCents: number;
currencyCode: string;
}): Promise<{
id: string;
state: "completed" | "declined";
}>;
}The differences are not merely naming conventions.
customerIdbecomescustomer.amountmust be converted into cents.currencybecomescurrencyCode.transactionIdmaps toid.- The provider's status values differ from the application's domain values.
One approach is to put these translations directly inside the application service:
class CheckoutService {
constructor(
private readonly client: AcmePayClient,
) {}
async checkout(customerId: string, amount: number) {
const result = await this.client.createPaymentIntent({
customer: customerId,
amountInCents: Math.round(amount * 100),
currencyCode: "USD",
});
return {
transactionId: result.id,
status:
result.state === "completed"
? "succeeded"
: "failed",
};
}
}This works, but the service now knows the provider's API, field names, units, and status conventions.
If another provider is introduced, the application service may need additional branching. If the provider changes its SDK, the service may need to change again.
Over time, the integration details become part of the application's business logic.
The problem is not that the external interface is poorly designed. The provider may have perfectly valid reasons for its own API.
The problem is that two independently designed interfaces are not necessarily compatible.
2. The Core Idea Behind the Adapter Pattern
The Adapter Pattern introduces an object that implements the interface expected by the client while delegating the actual work to an object with a different interface.
The structure is simple:
- Client: The application code that needs a particular capability.
- Target interface: The contract the application expects.
- Adaptee: The existing object whose interface does not match.
- Adapter: The object that translates between the two interfaces.
The relationship looks like this:
CheckoutService
|
v
PaymentGateway
|
v
AcmePayAdapter
|
v
AcmePayClient
|
v
External Payment APIThe client depends on the target interface, not on the concrete provider.
The adapter understands both sides. It translates application-level requests into provider-specific requests and converts provider responses into application-level results.
This separation creates an explicit boundary between your application and an external dependency.
It also makes provider replacement easier. A different provider can be integrated through another adapter, provided it can satisfy the same application contract.
The key idea is not to eliminate integration complexity. It is to contain that complexity in one place.
3. Implementing Adapter in TypeScript
Let's implement the payment example.
Step 1: Define the application contract
The application should describe what it needs, rather than what a particular SDK happens to offer.
interface PaymentGateway {
charge(input: {
customerId: string;
amount: number;
currency: string;
}): Promise<{
transactionId: string;
status: "succeeded" | "failed";
}>;
}This interface belongs to the application or domain boundary, depending on your architecture.
It expresses the capability required by the application without exposing the provider's request and response structures.
Step 2: Wrap the external client
Assume the provider SDK has already been initialized:
interface AcmePayClient {
createPaymentIntent(input: {
customer: string;
amountInCents: number;
currencyCode: string;
}): Promise<{
id: string;
state: "completed" | "declined";
}>;
}The adapter implements the application's interface and translates between the two contracts:
class AcmePayAdapter implements PaymentGateway {
constructor(
private readonly client: AcmePayClient,
) {}
async charge(input: {
customerId: string;
amount: number;
currency: string;
}) {
const result = await this.client.createPaymentIntent({
customer: input.customerId,
amountInCents: Math.round(input.amount * 100),
currencyCode: input.currency,
});
return {
transactionId: result.id,
status:
result.state === "completed"
? "succeeded" as const
: "failed" as const,
};
}
}The adapter performs three kinds of translation:
- Structural translation: Renaming fields and reshaping objects.
- Semantic translation: Mapping provider-specific statuses to application concepts.
- Representation translation: Converting units, formats, or data types.
These responsibilities are related, but they are not identical. Renaming a field is usually straightforward; converting money or interpreting provider status codes requires explicit assumptions about meaning.
For example, Math.round(amount * 100) is appropriate only if the application uses decimal major currency units and the provider expects minor units with two decimal places. Not every currency follows that rule.
A production implementation should use a money representation and currency-aware conversion rules rather than assume every currency has two decimal places.
Step 3: Inject the adapter into the application
The application service now depends only on the target interface:
class CheckoutService {
constructor(
private readonly payments: PaymentGateway,
) {}
async checkout(
customerId: string,
amount: number,
currency: string,
) {
return this.payments.charge({
customerId,
amount,
currency,
});
}
}The concrete adapter is selected at the composition boundary:
const providerClient: AcmePayClient =
createAcmePayClient();
const paymentGateway: PaymentGateway =
new AcmePayAdapter(providerClient);
const checkoutService =
new CheckoutService(paymentGateway);createAcmePayClient() represents the provider SDK's initialization, not a built-in function.
The important distinction is that CheckoutService does not instantiate AcmePayAdapter or initialize the provider SDK itself.
The composition boundary decides which implementation to use.
This works naturally with Dependency Injection, but Adapter and Dependency Injection solve different problems. Adapter translates an interface; Dependency Injection supplies the chosen implementation.
Step 4: Test the application independently
Because the application depends on an interface, its business logic can be tested without contacting the provider:
class FakePaymentGateway implements PaymentGateway {
async charge() {
return {
transactionId: "test-transaction",
status: "succeeded" as const,
};
}
}A test can inject the fake gateway into CheckoutService.
Separately, the adapter should be tested to verify that it translates requests and responses correctly. For example, a test should check the amount conversion, customer identifier mapping, and provider status mapping.
These tests answer different questions:
- Application tests verify business behavior.
- Adapter tests verify integration translation.
- A smaller number of integration tests verify that the real SDK and provider behave as expected.
An adapter does not remove the need to test the external integration. It makes the responsibilities easier to test independently.
4. Adapting Third-Party APIs and SDKs
Payment providers are only one example. Adapters are useful whenever an external interface differs from the contract your application wants to use.
4.1. Storage providers
An application might define a storage interface:
interface FileStorage {
upload(input: {
key: string;
content: Uint8Array;
contentType: string;
}): Promise<void>;
}An AWS S3 SDK, an Azure Blob client, and a local filesystem library all have different APIs.
Instead of letting business services depend on each SDK, you can implement a separate adapter for each storage backend.
The application uses FileStorage; the adapters handle provider-specific request formats, credentials, response metadata, and error conversion.
However, a shared interface should represent genuinely shared capabilities. If one provider supports versioning, signed URLs, or conditional writes and another does not, avoid pretending these features are universally available.
A useful abstraction exposes the capabilities the application actually requires, not every feature that any provider happens to offer.
4.2. Legacy systems
Adapters can also isolate legacy interfaces.
Suppose an older customer system exposes a method such as:
interface LegacyCustomerClient {
findCustomerByCode(
code: string,
): Promise<{
CUST_NO: string;
FULL_NAME: string;
ACTIVE_FLAG: "Y" | "N";
} | null>;
}The rest of the application may prefer a modern domain representation:
interface Customer {
id: string;
name: string;
active: boolean;
}An adapter translates the legacy representation:
class LegacyCustomerAdapter {
constructor(
private readonly client: LegacyCustomerClient,
) {}
async findById(id: string): Promise<Customer | null> {
const record =
await this.client.findCustomerByCode(id);
if (!record) {
return null;
}
return {
id: record.CUST_NO,
name: record.FULL_NAME,
active: record.ACTIVE_FLAG === "Y",
};
}
}The adapter prevents legacy field names and conventions from leaking throughout the application.
This can be particularly valuable during gradual migrations. The application can move toward a cleaner internal model while the legacy system remains operational.
4.3. Normalize errors deliberately
External systems often represent failures differently. One SDK may throw an exception, another may return an error object, and a third may expose provider-specific status codes.
An adapter can translate known failures into application-level errors:
class PaymentUnavailableError extends Error {}
class AcmePayErrorAdapter {
translate(error: unknown): Error {
if (isAcmePayUnavailableError(error)) {
return new PaymentUnavailableError(
"The payment service is temporarily unavailable.",
);
}
return error instanceof Error
? error
: new Error("An unknown payment error occurred.");
}
}Here, isAcmePayUnavailableError() represents a provider-specific type guard that must be implemented against the actual SDK.
The principle is to translate errors only when their meaning is understood. Not every timeout, rejection, or provider error should become the same generic exception.
In payment systems, for example, a timeout does not necessarily mean the payment failed. The provider may have processed the request but failed to return a response. Retrying blindly could create a duplicate charge.
A good adapter preserves enough information for the application to make safe decisions, including whether a failure is retryable and whether the operation's outcome is uncertain.
5. Adapter vs. Decorator, Proxy, and Facade
These patterns can look similar because each may wrap an existing object. Their purposes differ.
| Pattern | Primary purpose | Typical example |
|---|---|---|
| Adapter | Translate one interface into another | Make a vendor SDK implement an application contract |
| Decorator | Add behavior while preserving an interface | Add logging, caching, or retry behavior |
| Proxy | Control access to an object | Lazy initialization or access checks |
| Facade | Simplify interaction with a subsystem | Provide one API over several complex services |
Consider a payment gateway.
An AcmePayAdapter translates the application's charge() operation into the provider's createPaymentIntent() operation.
A LoggingPaymentGateway could decorate the gateway with logging while preserving the PaymentGateway interface.
A PaymentGatewayProxy might restrict access or delay creating the underlying client until it is needed.
A CheckoutFacade might coordinate payment, inventory, and order creation behind one higher-level operation.
These patterns can also be combined. A provider adapter might be wrapped by a logging decorator and then supplied through a dependency injection container.
The important question is not whether an object wraps another object. It is what responsibility the wrapper owns.
6. Common Adapter Mistakes
6.1. Leaking provider-specific types
Consider an adapter that returns a provider SDK response directly:
interface PaymentGateway {
charge(input: ChargeInput): Promise<AcmePayResponse>;
}The application still depends on AcmePayResponse, even though the interface appears to abstract the provider.
If the SDK changes, application code and tests may need to change as well.
Prefer application-owned input and output types where a genuine boundary is needed. Provider types can remain inside the adapter implementation.
6.2. Building an abstraction around only superficial differences
Suppose two services both provide a send() method, but one guarantees delivery and the other only accepts a message for asynchronous processing.
Giving them a shared send() interface does not make their behavior equivalent.
An adapter should translate semantics, not just method names. If the underlying capabilities differ significantly, the application contract should represent that difference rather than hide it.
6.3. Swallowing errors during translation
This is dangerous:
async charge(input: ChargeInput) {
try {
return await this.client.createPaymentIntent(
toProviderRequest(input),
);
} catch {
return {
transactionId: "",
status: "failed" as const,
};
}
}It turns every error into an apparently valid result. The caller cannot distinguish a declined payment from a network failure or a programming error.
Translate errors according to documented semantics. Preserve meaningful context, and let unexpected failures remain observable.
6.4. Creating a universal interface that fits nobody
A single interface designed to support every imaginable provider often accumulates optional fields, capability flags, and methods that some implementations cannot support.
For example:
interface UniversalPaymentProvider {
charge?: Function;
refund?: Function;
authorize?: Function;
capture?: Function;
supportsPartialRefund?: boolean;
}This is not a useful contract. It pushes capability checking and uncertainty onto every consumer.
Prefer a small interface that reflects the application's actual requirements. Introduce separate capability interfaces when the application genuinely needs additional operations.
6.5. Hiding important differences
Abstraction should reduce irrelevant differences, not erase important ones.
If one provider supports idempotency keys, another has different timeout guarantees, or a third uses asynchronous settlement, those distinctions may affect application correctness.
Keep such differences explicit when the business logic needs them. The adapter should simplify integration without making guarantees the underlying provider cannot fulfill.
7. When Should You Use Adapter?
The Adapter Pattern is especially useful when:
- Integrating third-party APIs or SDKs with interfaces that differ from your application contracts.
- Replacing a legacy system gradually without spreading its conventions throughout the codebase.
- Supporting multiple providers behind a common application-owned interface.
- Isolating data format, unit, status, and error translations.
- Testing application logic independently from external infrastructure.
It may be unnecessary when:
- A small application has one stable dependency and no meaningful interface mismatch.
- A thin wrapper simply renames one method without creating a useful boundary.
- The abstraction hides important differences that callers must understand.
- A framework already provides an appropriate adapter and adding another layer would only duplicate it.
There is also a practical design consideration: the best adapter usually lives close to the boundary it translates.
Provider-specific mapping belongs in the provider adapter, not scattered across controllers, domain services, and repositories. At the same time, avoid turning the adapter into a general-purpose integration framework before you have real requirements for one.
A useful starting point is a small application-owned interface, one concrete adapter, and tests for the translation rules. Add more abstractions only when the system's actual needs justify them.
Summary
The Adapter Pattern solves a specific design problem: an existing component provides the right capability through the wrong interface.
Instead of modifying application logic to accommodate every external dependency, the adapter translates between the external contract and the interface the application expects.
In practice, a good adapter:
- Defines a clear boundary around external dependencies.
- Translates request and response structures, units, and semantics.
- Keeps provider-specific types and conventions from leaking into application code.
- Preserves meaningful error information and behavioral guarantees.
- Makes testing and provider replacement easier without pretending all providers are identical.
But an adapter is not automatically good architecture. An unnecessary adapter adds indirection, and an overly broad interface can hide more complexity than it removes.
The goal is not to wrap every dependency. It is to isolate the differences that would otherwise make your application harder to change.
A well-designed adapter lets your application speak its own language while still working with systems that speak a different one.
- Design Patterns
- Adapter Pattern
- OOP
- Programing
- Software Architecture