Our app sends login codes by SMS through two providers, so that a login still works when one of them is down. Each provider ships its own Java client, and the clients agree on almost nothing. One wants the phone number as a single run of digits, 919876543210. The other wants +91 and 9876543210 as separate values. One counts how long a message stays valid in minutes, the other in seconds. One reports a failure with a status code, the other throws its own checked exception. We cannot change either client.
The Adapter pattern puts one small class between our code and each vendor's client. Our code talks only to an interface we designed for our own needs. Each adapter turns that interface into calls on one vendor's client, and turns the vendor's answers back into our types. The same problem shows up with two payment gateways, two map services, an old internal service with an awkward API, and inside Java itself: InputStreamReader adapts a stream of bytes to Reader, the type Java uses for reading characters.
In this article we build a sender for one-time passwords (OTPs) twice. The first version calls both vendor clients straight from the business code. The second puts an adapter in front of each. Then we look at what the pattern costs, how it differs from Decorator and Facade, and how it comes up in interviews. Every snippet without a Sketch label is cut from a project that compiles and runs. A snippet from the finished project has an Open file button that shows the whole file.
The SMS sender we are building
The sender must do six things:
- Send a six-digit login code to a phone number. The code is valid for 5 minutes.
- Work with two providers, QuickSMS and TextLane, whose client classes we cannot change.
- Fall back. If the first provider fails for a reason of its own (it is down, it is rate limiting us, or something unexpected went wrong), try the other one.
- Stop on a bad number. If a provider says the number does not exist, give up. The other provider cannot reach it either.
- Report the result: which provider sent the message and its message id, or that a provider took it without confirming, or why nobody could.
- Keep the business code ignorant. The OTP service must not know which providers exist.
Here are the two vendor methods we have to call. QuickSMS returns a response with a status code:
// msisdn is the country code and the number as one run of digits, with no "+". public Response dispatch(String msisdn, String body, int ttlMinutes) {TextLane returns a message id, and throws a checked exception on failure:
// countryCode starts with "+"; localNumber is the number without it. public String sendText(String countryCode, String localNumber, String content, long validitySeconds) throws TextLaneException {Side by side, the differences are:
| QuickSMS | TextLane | |
|---|---|---|
| Phone number | 919876543210, one string of digits | "+91" and "9876543210", two strings |
| How long the message stays valid | int ttlMinutes | long validitySeconds |
| Success | status 202 and a message id | returns the message id |
| Failure | status 400, 429, 503 and others | throws TextLaneException with a code such as "THROTTLED" |
This figure is the one to draw first in an interview. It puts a line between our side, where everything uses our types, and their side, where each vendor uses its own. Every difference in the table above sits on that line, and an adapter is the class that lives there.
The first version: the vendors inside the business code
The obvious way to write this is to call the vendor clients straight from the OTP service, with an if on which provider comes first:
public String sendLoginCode(PhoneNumber to) { int code = codes.getAsInt(); String text = String.format("Your login code is %06d. It expires in 5 minutes.", code); String msisdn = to.countryCode() + to.nationalNumber(); String countryCode = "+" + to.countryCode(); if (primary == Provider.QUICKSMS) { QuickSmsClient.Response response = quickSms.dispatch(msisdn, text, 5); if (response.statusCode() == 202) { return "QuickSMS " + response.messageId(); } if (response.statusCode() == 400) { throw new IllegalArgumentException("No such number: " + to); } return sendWithTextLane(countryCode, to.nationalNumber(), text); } try { return "TextLane " + textLane.sendText(countryCode, to.nationalNumber(), text, 300); } catch (TextLaneException e) { if ("INVALID_DESTINATION".equals(e.errorCode())) { throw new IllegalArgumentException("No such number: " + to); } QuickSmsClient.Response response = quickSms.dispatch(msisdn, text, 5); if (response.statusCode() == 202) { return "QuickSMS " + response.messageId(); } int status = response.statusCode(); throw new IllegalStateException("Both providers failed, QuickSMS status " + status); } }This code sends codes, and with one provider and one caller its shape would be fine. It already has a gap that is hard to see: if the QuickSMS client throws instead of returning a status, nothing falls back. The trouble grows as the code grows.
Vendor details live in business code. The digits-only number, the + prefix, status 202 and 400, the string "INVALID_DESTINATION": all of it is in OtpService, a class whose job is login codes.
The units are easy to mix up. The 5 on line 32 is minutes, and the 300 on line 42 is seconds. Both are plain numbers, so swapping them still compiles. Nothing in the types says which is which.
Every sender repeats it. Order updates and delivery alerts also send SMS. Each one needs the same translation, so three senders and two providers make six places that know vendor details.
Vendor types leak everywhere. OtpService imports QuickSmsClient, TextLaneApi and TextLaneException. A test of the OTP service needs both vendor clients. A third provider means a new branch in every sender.
The idea
The pattern works like this:
- We write the interface our code wants, in our own types:
SmsSender, with one method,send(PhoneNumber, SmsMessage), which returns anSmsReceiptor throws anSmsException. - For each vendor, one adapter class implements that interface and holds the vendor's client.
- On the way in, the adapter turns our types into the vendor's: the number format, the units, the method to call.
- On the way out, it turns the vendor's answer into ours: a receipt, or our own exception with a reason we defined.
- Business code holds an
SmsSenderand never sees a vendor type.
The pattern has four names for its parts. The interface our code wants, SmsSender, is the target. A vendor's class, such as QuickSmsClient, is the adaptee. The class in between is the adapter. The code that calls the target, here OtpService, is the client.
Building it, step by step
Step 1: our own interface, in our own types
The interface has one method, and every type in it is ours:
public interface SmsSender { // Returns a receipt when a provider confirms it took the message. Otherwise throws SmsException; // the reason UNCONFIRMED means a provider took it without a message id. SmsReceipt send(PhoneNumber to, SmsMessage message);PhoneNumber and SmsMessage are records that check their values when they are created. A PhoneNumber holds a country code of 1 to 3 digits and a number of 6 to 12 digits, with at least 8 digits in all. QuickSMS needs that many, and we apply it to every number as our rule for a full number. An SmsMessage holds the text and how long the message stays valid:
public record SmsMessage(String text, Duration validity) { public static final int MAX_LENGTH = 160; public static final Duration MIN_VALIDITY = Duration.ofMinutes(1); public static final Duration MAX_VALIDITY = Duration.ofDays(1); public SmsMessage { Objects.requireNonNull(text, "text"); Objects.requireNonNull(validity, "validity"); if (text.isBlank()) { throw new IllegalArgumentException("Text must not be blank"); } if (text.length() > MAX_LENGTH) { throw new IllegalArgumentException("Text is longer than " + MAX_LENGTH + " characters"); } if (validity.compareTo(MIN_VALIDITY) < 0 || validity.compareTo(MAX_VALIDITY) > 0) { throw new IllegalArgumentException("Validity must be 1 minute to 1 day: " + validity); } }A message has at most 160 characters, and stays valid for between 1 minute and 1 day. Duration is a real type here, not a number of minutes or seconds, so the unit question from the first version cannot come up on our side at all. It is answered once, inside each adapter.
These checks throw exceptions because a bad value at this point is a bug. A person who types a wrong phone number should get a message from the sign-up form, long before the number reaches PhoneNumber. The same split runs through the whole design: SmsException is for things that go wrong at a provider and can happen to correct code, and IllegalArgumentException or NullPointerException means the calling code has a bug.
Whose shape does our interface take?
Copy the first vendor's API
The interface would be dispatch(msisdn, body, ttlMinutes), returning a status code. The QuickSMS adapter becomes almost empty. But the TextLane adapter must invent status codes for TextLane's exceptions, and our business code now thinks in QuickSMS's terms. If we ever drop QuickSMS, our code is still shaped like a vendor we no longer use.
Design it for our own needsOur pick
send(PhoneNumber, SmsMessage) says what our code means, in types that check themselves. Every adapter translates, including the one for the first vendor. That costs a little code in each adapter, and in return no vendor gets a special place.
Step 2: the QuickSMS adapter
The adapter holds a QuickSmsClient and implements SmsSender:
public class QuickSmsAdapter implements SmsSender { static final String PROVIDER = "QuickSMS"; private final QuickSmsClient client; public QuickSmsAdapter(QuickSmsClient client) { this.client = Objects.requireNonNull(client, "client"); } @Override public SmsReceipt send(PhoneNumber to, SmsMessage message) { Objects.requireNonNull(to, "to"); Objects.requireNonNull(message, "message"); String msisdn = to.countryCode() + to.nationalNumber(); QuickSmsClient.Response response; try { response = client.dispatch(msisdn, message.text(), ttlMinutes(message.validity())); } catch (RuntimeException e) { throw new SmsException(PROVIDER, Reason.UNKNOWN, "client failed: " + e.getMessage(), e); } int status = response.statusCode(); if (status != 202) { throw new SmsException(PROVIDER, reasonFor(status), "status " + status, null); } if (response.messageId() == null) { String detail = "accepted without a message id"; throw new SmsException(PROVIDER, Reason.UNCONFIRMED, detail, null); } return new SmsReceipt(PROVIDER, response.messageId()); }Line 27 joins the country code and the number into QuickSMS's format. Line 31 makes the one call to the vendor. Lines 37 to 44 turn the response into ours. A status other than 202 becomes an SmsException with a reason. A 202 without a message id becomes UNCONFIRMED: QuickSMS took the message, but we have no id to prove it. If the vendor's client throws instead, for example on a dropped connection, the catch on line 32 wraps it in our exception and keeps it as the cause, so no vendor exception escapes. An Error, such as running out of memory, is not caught, on purpose: it is not a provider failure.
The two small helpers hold the rest of the translation:
// QuickSMS counts validity in whole minutes. A late code is useless, so we round down, // and SmsMessage never allows less than one minute. private static int ttlMinutes(Duration validity) { return Math.toIntExact(validity.toMinutes()); } // Our own checks run first, so a 400 can only mean the number. private static Reason reasonFor(int status) { return switch (status) { case 400 -> Reason.INVALID_NUMBER; case 429 -> Reason.RATE_LIMITED; case 503 -> Reason.UNAVAILABLE; default -> Reason.UNKNOWN; }; }QuickSMS counts validity in whole minutes, so 90 seconds has to become either 1 or 2. A login code that arrives after it expired is useless, so ttlMinutes rounds down. SmsMessage never allows less than a minute, so the result is never 0. The status codes map to reasons we defined, and anything we do not know becomes UNKNOWN.
Object adapter or class adapter?
Extend the vendor's class
The adapter would be class QuickSmsAdapter extends QuickSmsClient implements SmsSender. This works in Java when the vendor class is not final. But every public method of QuickSmsClient, including dispatch, is now public on our adapter too, so the vendor's API leaks right back out. The adapter is tied to that one concrete class, and a test cannot hand it a fake client.
Hold the vendor's client in a fieldOur pick
The adapter receives a QuickSmsClient in its constructor and exposes only send. A test can pass a client set up to fail, the demo does exactly that, and a final vendor class is no problem.
Step 3: errors become our errors
Every failure, from either vendor, reaches our code as one type:
public class SmsException extends RuntimeException { public enum Reason { INVALID_NUMBER, UNCONFIRMED, RATE_LIMITED, UNAVAILABLE, UNKNOWN } private final String provider; private final Reason reason; public SmsException(String provider, Reason reason, String detail, Throwable cause) { super(provider + ": " + detail, cause); this.provider = Objects.requireNonNull(provider, "provider"); this.reason = Objects.requireNonNull(reason, "reason"); } public String provider() { return provider; } public Reason reason() { return reason; } // Another provider cannot reach a number this one called invalid, and a message a provider // accepted without an id may already be on its way. Every other failure is worth another try. public boolean worthTryingElsewhere() { return reason != Reason.INVALID_NUMBER && reason != Reason.UNCONFIRMED; }The five reasons are the failure categories our code needs. UNCONFIRMED means a provider accepted the message but sent back no id, so the message may already be on its way. worthTryingElsewhere answers the one question the fallback will ask: is there any point sending this to another provider? For a number that does not exist, or a message that may already be sent, there is not.
TextLane needs more translation on the way out, because it reports failure with a checked exception and a string code:
@Override public SmsReceipt send(PhoneNumber to, SmsMessage message) { Objects.requireNonNull(to, "to"); Objects.requireNonNull(message, "message"); String messageId; try { messageId = api.sendText("+" + to.countryCode(), to.nationalNumber(), message.text(), message.validity().toSeconds()); } catch (TextLaneException e) { throw new SmsException(PROVIDER, reasonFor(e.errorCode()), "error " + e.errorCode(), e); } catch (RuntimeException e) { throw new SmsException(PROVIDER, Reason.UNKNOWN, "client failed: " + e.getMessage(), e); } if (messageId == null) { String detail = "accepted without a message id"; throw new SmsException(PROVIDER, Reason.UNCONFIRMED, detail, null); } return new SmsReceipt(PROVIDER, messageId); } private static Reason reasonFor(String errorCode) { if (errorCode == null) { return Reason.UNKNOWN; } return switch (errorCode) { case "INVALID_DESTINATION" -> Reason.INVALID_NUMBER; case "THROTTLED" -> Reason.RATE_LIMITED; case "UNAVAILABLE" -> Reason.UNAVAILABLE; default -> Reason.UNKNOWN; }; }Lines 30 and 31 add the + and pass the validity in seconds. Line 33 turns TextLane's checked exception into ours, keeping it as the cause so the vendor's own message stays available in the logs. Line 35 does the same for anything unexpected the client throws. Lines 46 to 48 handle a failure that carries no code at all, which would otherwise crash the switch with a NullPointerException.
How does a failure reach our code?
Let the vendor's exceptions through
This is the least code. But then every caller must catch TextLaneException and also check QuickSMS status codes. The vendor types we wanted to hide come straight back.
Return a status code, like QuickSMS
Every caller must remember to check it, and a forgotten check silently treats a failure as a success.
One exception type with a reason we defineOur pick
We throw SmsException with a reason we define, and keep the vendor's own exception as the cause. Callers handle a few cases that mean something to them, and the detail is not lost. The cost is that two vendor codes which differ in some small way end up as the same reason.
Checked or unchecked?
A checked exception
The compiler makes every caller of send handle it. But every layer between OtpService and the login page must then catch it or declare it, including code that can do nothing useful about a failed SMS.
An unchecked exceptionOur pick
SmsException extends RuntimeException. The code that can act on it, such as the login page that shows "try again", catches it, and the layers in between stay clean. The cost is that nothing forces a caller to think about failure, so the comment on SmsSender.send says that it throws.
Step 4: what the adapter must not do
An adapter only translates. It does not retry, choose a provider, write the message text or decide what a failure means for the business. Those are rules, and a rule inside one adapter is missing from the other one.
The fallback from requirement 3 is such a rule, so it gets its own class. It implements SmsSender too, and holds the senders it tries, in order:
@Override public SmsReceipt send(PhoneNumber to, SmsMessage message) { List<SmsException> failures = new ArrayList<>(); List<RuntimeException> logFailures = new ArrayList<>(); for (SmsSender sender : senders) { try { return sender.send(to, message); } catch (SmsException failure) { report(failure, logFailures); failures.add(failure); if (!failure.worthTryingElsewhere()) { break; } } } throw giveUp(failures, logFailures); } // A new exception, so the senders' own exceptions are never changed. private static SmsException giveUp(List<SmsException> failures, List<RuntimeException> logFailures) { SmsException last = failures.get(failures.size() - 1); SmsException giveUp = new SmsException(last.provider(), last.reason(), "gave up after " + failures.size() + " provider(s)", last); for (SmsException earlier : failures.subList(0, failures.size() - 1)) { giveUp.addSuppressed(earlier); } for (RuntimeException logFailure : logFailures) { giveUp.addSuppressed(logFailure); } return giveUp; } // A broken log must not stop the next provider from being tried. private void report(SmsException failure, List<RuntimeException> logFailures) { try { log.providerFailed(failure); } catch (RuntimeException logFailure) { if (logFailure != failure) { logFailures.add(logFailure); } } }The loop tries each sender in turn and returns the first receipt (line 35). On a failure it logs it, keeps it, and moves on, unless the failure is not worth trying elsewhere (lines 39 to 41). If nobody succeeds, line 44 throws a new SmsException. The last failure is its cause and sets its reason, and the earlier failures are attached as suppressed exceptions, so the caller sees every attempt. Building a new exception means the providers' own exceptions are never changed, which matters when a sender throws the same object twice. An exception that is not an SmsException is not caught at all: it means a bug in an adapter, and it goes straight to the caller. The constructor also refuses an empty list and a sender listed twice.
Lines 63 to 70 make sure the log cannot break the fallback. If writing the log throws, the next provider is still tried, and the log's error is attached to the final exception if every provider fails.
Where does the fallback live?
Inside the QuickSMS adapter
On a failure, the QuickSMS adapter calls TextLane. Now one adapter knows about another vendor, the order of providers is fixed in code, and the TextLane adapter has no fallback at all.
In its own sender that wraps the othersOur pick
FallbackSmsSender holds a list of SmsSenders and knows nothing about any vendor. The order is chosen where the senders are built, and a third provider is one more item in the list. Because it is an SmsSender itself, the OTP service cannot tell it apart from a single adapter.
An UNKNOWN failure, such as a dropped connection, might mean the first provider did send the message, or might mean it did not. The fallback sends it again, because a login code that never arrives is worse than one that arrives twice, and both messages carry the same code. UNCONFIRMED is different: the provider said yes. A second send would only pay for a duplicate message, so the fallback stops, and the OTP service tells the user the code may take a moment.
A provider that hangs is a different problem. If QuickSMS never answers, dispatch blocks and the fallback never starts. The timeout belongs in the vendor client's own settings, set where the client is built, so a hang becomes an exception that the adapter maps to UNKNOWN. A provider that keeps failing can also be skipped for a while: a circuit breaker, a decorator around an adapter, stops calling it after repeated failures. Neither is in this project.
Step 5: the business code
With the translation and the fallback in place, the OTP service only knows about SMS in our own terms:
public class OtpService { private static final Duration CODE_LIFETIME = Duration.ofMinutes(5); private static final int LARGEST_CODE = 999_999; private static final String TEXT = "Your login code is %06d. It expires in %d minutes."; private final SmsSender sms; private final IntSupplier codes; public OtpService(SmsSender sms, IntSupplier codes) { this.sms = Objects.requireNonNull(sms, "sms"); this.codes = Objects.requireNonNull(codes, "codes"); } // A receipt means the code was sent. Empty means a provider took it without confirming, so the // user should wait for it rather than ask for another code. public Optional<SmsReceipt> sendLoginCode(PhoneNumber to) { Objects.requireNonNull(to, "to"); int code = codes.getAsInt(); if (code < 0 || code > LARGEST_CODE) { throw new IllegalStateException("Code generator returned " + code); } String text = String.format(Locale.ROOT, TEXT, code, CODE_LIFETIME.toMinutes()); try { return Optional.of(sms.send(to, new SmsMessage(text, CODE_LIFETIME))); } catch (SmsException e) { if (e.reason() == Reason.UNCONFIRMED) { return Optional.empty(); } throw e; } }Apart from the Java library, it imports only our own sms package. It builds the text, pads the code to six digits, and makes one call on line 39. Locale.ROOT on line 37 keeps the digits as 0 to 9 whatever the server's language setting is. An UNCONFIRMED failure becomes an empty result (lines 40 to 43), so the login page says "code sent, it may take a moment" instead of offering another code. One place decides which providers exist and in which order: the code that creates the objects.
public static void main(String[] args) { QuickSmsClient quickSms = new QuickSmsClient(); TextLaneApi textLane = new TextLaneApi(); SendLog log = failure -> System.out.println( " failed: " + failure.getMessage() + " (" + failure.reason() + ")"); SmsSender sms = new FallbackSmsSender( List.of(new QuickSmsAdapter(quickSms), new TextLaneAdapter(textLane)), log); PrimitiveIterator.OfInt codes = IntStream.of(482913, 105522, 31337, 770041, 609114).iterator(); OtpService otp = new OtpService(sms, codes::nextInt);The finished design
Here is the second send from the demo, with QuickSMS down:
The whole project is below. Click any class name in the code to open that class.
package adapter; import java.time.Duration;import java.util.Objects; import sms.PhoneNumber;import sms.SmsException;import sms.SmsException.Reason;import sms.SmsMessage;import sms.SmsReceipt;import sms.SmsSender;import vendor.QuickSmsClient; public class QuickSmsAdapter implements SmsSender { static final String PROVIDER = "QuickSMS"; private final QuickSmsClient client; public QuickSmsAdapter(QuickSmsClient client) { this.client = Objects.requireNonNull(client, "client"); } @Override public SmsReceipt send(PhoneNumber to, SmsMessage message) { Objects.requireNonNull(to, "to"); Objects.requireNonNull(message, "message"); String msisdn = to.countryCode() + to.nationalNumber(); QuickSmsClient.Response response; try { response = client.dispatch(msisdn, message.text(), ttlMinutes(message.validity())); } catch (RuntimeException e) { throw new SmsException(PROVIDER, Reason.UNKNOWN, "client failed: " + e.getMessage(), e); } int status = response.statusCode(); if (status != 202) { throw new SmsException(PROVIDER, reasonFor(status), "status " + status, null); } if (response.messageId() == null) { String detail = "accepted without a message id"; throw new SmsException(PROVIDER, Reason.UNCONFIRMED, detail, null); } return new SmsReceipt(PROVIDER, response.messageId()); } // QuickSMS counts validity in whole minutes. A late code is useless, so we round down, // and SmsMessage never allows less than one minute. private static int ttlMinutes(Duration validity) { return Math.toIntExact(validity.toMinutes()); } // Our own checks run first, so a 400 can only mean the number. private static Reason reasonFor(int status) { return switch (status) { case 400 -> Reason.INVALID_NUMBER; case 429 -> Reason.RATE_LIMITED; case 503 -> Reason.UNAVAILABLE; default -> Reason.UNKNOWN; }; }}The demo in demo/Main.java sends five login codes. It switches the simulated vendors between working and failing, and prints what each vendor received:
1. Both providers up
sent: QuickSMS QS-1001
QuickSMS got msisdn=919876543210 ttlMinutes=5
body: Your login code is 482913. It expires in 5 minutes.
2. QuickSMS is down
failed: QuickSMS: status 503 (UNAVAILABLE)
sent: TextLane tl_501
TextLane got countryCode=+91 localNumber=9876543210 validitySeconds=300
3. Both providers down
failed: QuickSMS: status 503 (UNAVAILABLE)
failed: TextLane: error THROTTLED (RATE_LIMITED)
gave up: RATE_LIMITED, providers tried: 2
4. A number that does not exist
failed: QuickSMS: status 400 (INVALID_NUMBER)
gave up: INVALID_NUMBER, providers tried: 1
5. QuickSMS accepts the message but sends back no id
failed: QuickSMS: accepted without a message id (UNCONFIRMED)
sent, not confirmed: tell the user the code may take a momentFollow the five steps. In step 1 QuickSMS sends the code, and its client received 919876543210 and ttlMinutes=5: the adapter's translation, made visible. In step 2 QuickSMS answers 503, the fallback logs it, and TextLane sends the code. TextLane received +91, the number on its own, and 300 seconds. In step 3 both providers fail, and the caller gets the last failure, RATE_LIMITED, after two tries. In step 4 the number ends in 0000, which the simulated networks treat as a number that does not exist. QuickSMS answers 400, the reason is INVALID_NUMBER, and TextLane is never tried. In step 5 QuickSMS accepts the message but sends back no id. The fallback stops at UNCONFIRMED, and the OTP service reports a code that may take a moment.
What it costs
The pattern makes one kind of change cheap and another expensive.
Adding a provider is cheap. A third provider is one new adapter class and one more item in the list where the senders are built. OtpService, the fallback and the other adapters do not change.
Changing our interface is expensive. Suppose we want delivery reports: status(messageId), to ask whether a message reached the phone. Every adapter must find the matching call in its vendor's client and translate its answer. The fallback must decide which provider to ask. A vendor that has no such call cannot support the new method at all, and no adapter can hide that.
There are smaller costs too:
- There is one more class per vendor, and one more layer to step through when following a send in a debugger.
- Translation can lose detail. QuickSMS rounds validity to whole minutes, and many vendor error codes fold into five reasons. Keeping the vendor's exception as the cause keeps that detail.
- An adapter cannot add what the vendor lacks. If a vendor cannot do something, the adapter can only refuse.
When an adapter is too much
If there is one provider, one piece of code that sends SMS, and no plan to change either, the adapter is a class that only forwards. A small private method in the one sender that needs it is enough:
private static final int CODE_LIFETIME_MINUTES = 5; private SmsReceipt send(PhoneNumber to, String text) { String msisdn = to.countryCode() + to.nationalNumber(); QuickSmsClient.Response response = quickSms.dispatch(msisdn, text, CODE_LIFETIME_MINUTES); if (response.statusCode() != 202) { throw new IllegalStateException("QuickSMS returned " + response.statusCode()); } return new SmsReceipt("QuickSMS", response.messageId());}The adapter earns its place when a second caller or a second vendor appears.
Adapter or Decorator?
The two are easy to confuse, because both are a class that holds another object and forwards calls to it. The difference is in what happens to the interface.
| Adapter | Decorator | |
|---|---|---|
| Why it exists | To make an existing class fit an interface it does not implement | To add a job (retries, caching, timing) to an object |
| Interface going in and coming out | Different: our SmsSender outside, the vendor's dispatch inside | The same on both sides |
| How many | Usually one per vendor class | Several, stacked in an order chosen where they are built |
| Example | QuickSmsAdapter around QuickSmsClient | A retry layer around a price lookup client, from the Decorator page |
A short way to remember it: an adapter changes the shape of an object, and a decorator adds behaviour behind the same shape.
Facade is the third look-alike. A facade puts one simple interface in front of a group of classes, so callers do not need to know the group, for example one checkout() method over cart, payment and stock services. An adapter makes one existing class fit the interface its callers need. A facade simplifies, and an adapter translates.
In an interview
The Adapter pattern sits inside low-level design questions that touch an outside system: two payment gateways in a checkout, two map providers in a ride-hailing app, notification channels, an old internal service during a migration. The signal in the question is a phrase such as "the app must support providers A and B" or "we are switching vendors".
We suggest presenting it in this order:
- Draw the boundary. Put our code on one side and the vendor clients on the other, and list what differs: formats, units, how failure is reported.
- Write our interface first, in our own types. Say why it is not a copy of either vendor's API.
- Write one adapter in full, including the error mapping. The real decisions are in the error mapping.
- Say where the rules live: retries and fallback in their own class, never inside an adapter.
Mistakes to avoid:
- An interface copied from the first vendor. It makes every other adapter translate into a vendor's terms, and it outlives that vendor.
- Vendor types leaking out. A vendor exception, response class or error-code string in business code means the adapter is not finished.
- Business rules inside an adapter. Fallback, retries and message text belong in their own classes, so every vendor gets the same rules.
- Unnamed unit conversions. A bare
* 60or/ 60with no name invites the minutes-and-seconds mix-up. Put each conversion in one named method, and decide how it rounds. - Treating every failure the same. Retrying a number that does not exist on every provider wastes calls and delays the answer to the user.
- A class adapter in Java that extends the vendor's class, so the vendor's methods leak through the adapter.
Summary
- Use an adapter when your code must work with a class whose interface you cannot change and do not want to depend on: a vendor client, a legacy service, a library.
- Design the target interface for your own needs, in your own types. Do not copy any vendor's API.
- Each adapter translates both ways: formats and units going in, answers and failures coming out. Keep the vendor's exception as the cause.
- Hold the vendor's client in a field rather than extending its class.
- Keep rules such as fallback and retries out of adapters, in classes that work with any
SmsSender. - A new vendor is one new adapter. A new method on your interface touches every adapter.