📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Adapter pattern? Show how you would wrap a third-party payment SDK behind your own interface, explain object versus class adapters, and say what belongs inside the adapter and what does not.

Adapter intent, object vs class adapter, wrapping a vendor SDK (Stripe.net) behind a domain interface, translating units, types and exceptions, .NET examples (StreamReader, TaskCompletionSource, Serilog's ILoggerProvider), and keeping business logic out of adapters.

Junior Theory Beginner adapter anti-corruption-layer dependency-inversion design-patterns payments testing

🎯 Key points

  • Adapter converts the interface of an existing class (adaptee) into the interface clients expect (target) without changing either
  • Object adapter holds the adaptee by composition (usual in C#); class adapter inherits the adaptee and implements the target, limited by single class inheritance
  • Wrapping a vendor SDK: your interface (IPaymentGateway) is shaped by your domain, the adapter translates to the SDK (PaymentIntentService.CreateAsync); an interface that mirrors the SDK just renames the coupling
  • The adapter translates types and units (decimal AUD to long cents), status codes and vendor exceptions (StripeException) into domain results
  • Benefits: vendor types and SDK version upgrades stay inside one class, tests use a hand-written fake or an NSubstitute/Moq double of your own interface, and switching or adding a provider touches one class
  • .NET examples: StreamReader adapts a byte Stream to TextReader, TaskCompletionSource adapts callback or event APIs to Task, Serilog's provider adapts Serilog to ILogger
  • Keep business rules out of the adapter: it translates, it doesn't decide (no discount or fraud logic)
  • At system scale the same idea is DDD's anti-corruption layer

⏱ 30-second answer

Adapter converts the interface of an existing class into the interface your code expects, without changing either side. It's a translator.

  • An object adapter wraps the adaptee by composition. This is the normal C# form.
  • A class adapter inherits the adaptee and implements the target. C# allows only one base class, so it's rare.

For a payment SDK, I define IPaymentGateway in my domain's terms. A StripePaymentGateway adapter then turns it into SDK calls, translating types and units (decimal AUD to cents), statuses and vendor exceptions into domain results. That keeps vendor types out of the codebase, lets tests use a fake, and confines a provider change to one class.

The trade-off is an extra layer. Keep it thin: an adapter translates, and business rules don't belong in it.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Adapter is a translator between two interfaces that don't match. My code expects one shape, the target. An existing class, the adaptee, offers another. The adapter implements the target and calls the adaptee, so neither has to change. In C# it's almost always an object adapter: the adapter holds the adaptee in a field and delegates. A class adapter inherits from the adaptee and implements the target, but with single inheritance and sealed SDK types it's rarely possible or wise.

A payment SDK is the classic case. I don't want Stripe's types all over my code, so I define IPaymentGateway in my own terms, something like ChargeAsync(Money amount, PaymentMethodToken token, CancellationToken ct) returning a PaymentResult. Then StripePaymentGateway implements it with the SDK's PaymentIntentService. The adapter's job is translation. Stripe wants amounts as a long in cents and a lowercase currency code, so $12.34 AUD becomes 1234 and "aud". It maps Stripe's statuses to my result type, and it catches StripeException and turns card declines into a domain result rather than letting a vendor exception leak out. The rest of the system only knows IPaymentGateway, so tests use a fake and adding a second provider is one new class. You see the same idea in the framework: StreamReader adapts a byte Stream into a TextReader, TaskCompletionSource adapts callback APIs into Tasks, and Serilog's provider adapts Serilog into ILogger.

The mistake I see is the adapter slowly gaining business logic, like retries, fraud rules or discounts, until it's the most important class in the system and tied to one vendor. An adapter should translate, not decide."


Structure

Role In the payment example
Target IPaymentGateway (your interface)
Adaptee Stripe.net PaymentIntentService
Adapter StripePaymentGateway
Client CheckoutService

Object vs class adapter

Object adapter Class adapter
Mechanism Composition (field) Inheritance
Works with sealed adaptee Yes No
Adapts subclasses of the adaptee Yes No
Can override adaptee behaviour No Yes
Typical in C# Yes Rare

What goes in the adapter

Belongs inside Belongs elsewhere
Unit and type conversion (decimal β†’ cents) Pricing, discounts, tax
Mapping vendor statuses and errors Fraud and business rules
Vendor authentication headers Retry and circuit breaker (resilience pipeline or decorator)
Vendor DTOs Domain entities

Production example

A retailer had Stripe types such as PaymentIntent and StripeException referenced in 60 files. When they added a bank-transfer option, the change touched most of those files and took three sprints. After moving everything behind an IPaymentGateway adapter, adding a second provider later took about four days and touched one project.

πŸ” What the interviewer is checking

Checks whether the candidate can isolate external dependencies cleanly and knows what an adapter should and shouldn't do.

Green flags

  • Defines target, adaptee and adapter correctly.
  • Prefers object adapters and explains why.
  • Designs the interface in domain terms and translates units and errors.
  • Keeps business logic out of the adapter.

Red flags

  • Interface mirrors the vendor SDK.
  • Vendor exceptions leak to callers.
  • Confuses Adapter with Decorator (adding behaviour) or Facade (simplifying).

πŸ“š Learn in depth

1. Structure

Client ──▢ Β«interfaceΒ» Target            Adaptee
             + Request()                  + SpecificRequest()
                  β–²                             β–²
                  β”‚ implements                  β”‚ holds (composition)
               Adapter β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               Request() => adaptee.SpecificRequest(translate(args))

2. Why own the interface

This is the Dependency Inversion Principle in action: the domain owns the abstraction (IPaymentGateway), and the infrastructure (the adapter) depends on it. The interface describes what your system needs, not what the vendor offers, so it is usually smaller than the SDK and named in domain language.

3. Translation responsibilities

Concern Example
Units AUD dollars (decimal) β†’ cents (long); timestamps from Unix seconds β†’ DateTimeOffset
Identifiers Your OrderId β†’ vendor metadata or idempotency key
Errors StripeException with card_declined β†’ PaymentResult.Declined; network error β†’ rethrow for resilience to handle
Async models Callback/event API β†’ Task via TaskCompletionSource<T>
Paging Vendor cursor pages β†’ IAsyncEnumerable<T>

4. Framework adapters

  • StreamReader/StreamWriter: byte stream β†’ text reader/writer (with decoding).
  • TaskCompletionSource<T>: any completion signal β†’ Task<T>; Task.Factory.FromAsync adapts the old Begin/End (APM) pattern.
  • Serilog.Extensions.Logging: Serilog ILogger β†’ Microsoft ILoggerProvider.
  • ReadOnlyCollection<T>: IList<T> β†’ read-only view.

5. From adapter to anti-corruption layer

When a whole external model (an ERP, a legacy system) doesn't fit your domain, a set of adapters plus translators forms an anti-corruption layer (DDD). Same idea, bigger scope.

Try it yourself

  1. Wrap System.Timers.Timer's Elapsed event in a method returning Task using TaskCompletionSource.
  2. Write IPaymentGateway and a fake; write a CheckoutService test that never references a vendor type.
  3. Search a codebase for vendor namespaces (using Stripe;) outside the infrastructure project.
  4. Add an architecture test (NetArchTest or ArchUnitNET) that fails if the domain references the SDK.

πŸ’» Code

A thin object adapter over Stripe.net that translates units, statuses and exceptions:

namespace Payments;

using Stripe;

public sealed record Money(decimal Amount, string Currency);
public sealed record PaymentResult(bool Succeeded, string? Reference, string? DeclineReason);

public interface IPaymentGateway   // owned by the domain, in domain language
{
    Task<PaymentResult> ChargeAsync(Guid orderId, Money amount, string paymentMethodToken, CancellationToken ct);
}

public sealed class StripePaymentGateway(PaymentIntentService intents) : IPaymentGateway
{
    public async Task<PaymentResult> ChargeAsync(Guid orderId, Money amount, string paymentMethodToken, CancellationToken ct)
    {
        var options = new PaymentIntentCreateOptions
        {
            Amount = (long)decimal.Round(amount.Amount * 100m, MidpointRounding.AwayFromZero),  // AUD dollars -> cents
            Currency = amount.Currency.ToLowerInvariant(),                                     // "AUD" -> "aud"
            PaymentMethod = paymentMethodToken,
            Confirm = true,
        };
        var request = new RequestOptions { IdempotencyKey = orderId.ToString() };             // safe to retry

        try
        {
            PaymentIntent pi = await intents.CreateAsync(options, request, ct);
            return pi.Status == "succeeded"
                ? new PaymentResult(true, pi.Id, null)
                : new PaymentResult(false, pi.Id, pi.Status);
        }
        catch (StripeException ex) when (ex.StripeError?.Type == "card_error")
        {
            return new PaymentResult(false, null, ex.StripeError.DeclineCode ?? ex.StripeError.Code);  // a decline is a result, not a crash
        }
        // Other StripeExceptions (network, 5xx) propagate so the resilience pipeline can handle them
    }
}

// Program.cs
// builder.Services.AddSingleton(new StripeClient(builder.Configuration["Stripe:SecretKey"]));
// builder.Services.AddSingleton(sp => new PaymentIntentService(sp.GetRequiredService<StripeClient>()));
// builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();

⚠ Common mistakes

  • Mistake: Letting vendor types (PaymentIntent, StripeException) appear in controllers and domain code. Why it is wrong: Every vendor change ripples through the system and tests need the SDK. Instead: Keep vendor types inside the adapter and expose domain types.
  • Mistake: Copying the vendor's API shape into your interface. Why it is wrong: You've renamed the SDK, not abstracted it; a second provider won't fit. Instead: Design the interface from what your use case needs.
  • Mistake: Putting business rules (discounts, fraud checks) in the adapter. Why it is wrong: Rules become vendor-specific and duplicated when you add a provider. Instead: Keep rules in the domain or application layer; the adapter only translates.
  • Mistake: Swallowing all vendor exceptions and returning "failed". Why it is wrong: Transient network errors then can't be retried and outages look like declines. Instead: Map expected outcomes (declines) to results and let transient failures propagate.
  • Mistake: Getting unit conversion wrong (dollars vs cents, rounding). Why it is wrong: You charge 100Γ— too much or lose a cent on rounding. Instead: Convert explicitly with defined rounding and test boundary values.
  • Mistake: Writing an adapter for a type you own. Why it is wrong: You can just change the class or its interface. Instead: Use Adapter for code you can't or shouldn't change (vendor, legacy, framework).

πŸ› Senior insight: trade-offs

Adapters are cheap insurance at system boundaries: payment providers, email and SMS services, identity providers, legacy systems. The value is containment: vendor churn, SDK upgrades and licensing changes stay inside one class. The risk is an adapter that grows into a hidden domain layer.

Option When it fits Cost When not to
Use the SDK directly Prototype, a single small call site Vendor types spread Core business flows
Thin adapter behind a domain interface Any external dependency on a core path One interface + class Code you own
Anti-corruption layer A large external model that conflicts with yours Translators, mapping tests A single simple API

I check adapter health with an architecture test (domain can't reference the vendor namespace) and by counting where vendor types appear.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions adding a second payment provider Why: Checks choosing between several adapters at run time
    How to answer

    This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:

    • Keyed services (.NET 8+): AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.
    • IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.
    • Typed resolver over keyed services: IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.

    To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.

  2. When: Candidate says the interface should be shaped by the domain, not the SDK Why: Checks designing a small, client-focused interface
    How to answer

    ISP says clients should not be forced to depend on methods they do not use. A fat interface such as IOrderService with 25 members couples every consumer to all of them, makes test doubles painful and pushes implementers to throw NotImplementedException. Split interfaces by what clients need (role interfaces): IOrderReader for queries, IOrderWriter for commands, IClock instead of a giant IUtilities. The BCL does this well (IReadOnlyCollection<T> versus ICollection<T>, IAsyncDisposable). Do not go to the extreme of one interface per method; group members that the same client uses together.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me