SteelReed

Search

Search posts, questions…

3. Advanced Java

Adapter and Factory: integrating a payment gateway and picking the right implementation

Reviewing an Adapter for a payment gateway that takes VND (a cast that drops cents, double for money, int overflow) and rewriting it with Money, a sealed result and currency-aware rounding. Then simple factory vs Factory Method vs Abstract Factory, a Spring bean registry, and two wiring traps: @RequiredArgsConstructor with non-final fields, injecting by a parent class.

18 Nov 20267 min readMid

–

1. The problem

OrderService works in USD, the payment SDK takes VND. The first adapter does (int) amount * 26000: a 12.99 USD order charges 312,000 VND (25,740 short), a 0.99 USD order charges 0, and a 99,999 USD order goes negative because int overflows.

2. Key idea

An adapter turns the interface of something you can't change into the interface you need. Business code only knows your port (PaymentGateway, Money, Paid/Declined), never the SDK's "00"/"51" codes. A factory is where the right implementation gets built or picked.

Simple factory Factory Method Abstract Factory
Shape switch or lookup table abstract method, subclass implements interface with several create methods
Produces one object of several kinds one object, subclass picks the kind a matching family of objects
Example booking service by listing type ReceiptSender email/SMS URL builder + verifier for one gateway

2.1 When to use which?

Tool Use when Don't use when
Adapter an SDK or external API has different types, units, errors both sides already share an interface (adding behavior is a Decorator)
switch on an enum under five kinds, rarely changes many teams add kinds
Registry Map<Type, Bean> many kinds, implementations in other modules one or two kinds
Abstract Factory objects must share a secret or algorithm you only pick one object

2.2 Which traps come up?

  • default in an enum switch: add RESORT and resorts silently take the default path. Drop default so the compiler flags the missing case.
  • @RequiredArgsConstructor only injects final fields: forget final and the field stays null, the app starts, the first request throws an NPE.
  • A timeout is "unknown": the gateway may already have charged. Treating it as failure and retrying with a new key charges twice.

3. In Java

JAVA
record Money(BigDecimal amount, Currency currency) { }
sealed interface PaymentResult permits Paid, Declined { }
 
final class LocalPayAdapter implements PaymentGateway {
    private final LocalPayClient sdk;     // injected, not new-ed
    private final FxRates fx;             // no hard-coded rate
 
    public PaymentResult charge(String ref, Money price) {
        BigDecimal vnd = fx.toVnd(price)                     // 12.99 USD -> 337746.495
            .setScale(0, RoundingMode.HALF_UP);              // 337746, per VND's Currency
        String code = sdk.charge(vnd.longValueExact(), ref); // throws on overflow instead of going wrong quietly
        return switch (code) {
            case "00" -> new Paid(ref, new Money(vnd, VND));
            case "51" -> new Declined(ref, Reason.INSUFFICIENT_FUNDS);
            default   -> new Declined(ref, Reason.UNKNOWN_CODE);
        };
    }
}

new BigDecimal("19.99"), not new BigDecimal(19.99). Currency.getDefaultFractionDigits() says VND has 0 decimals, USD 2.

Other languages: Go and TypeScript build adapters as a struct/class wrapping the client, with the same rule that money is an integer in minor units.

A Spring registry: a simple factory the container wires for you

Each bean declares type(); inject List<BookingHandler> and build an EnumMap. A missing or duplicate kind throws in the constructor, so the app refuses to start (fail fast).

JAVA
BookingHandlerRegistry(List<BookingHandler> handlers) {
    for (BookingHandler h : handlers)
        if (byType.putIfAbsent(h.type(), h) != null) throw new IllegalStateException("two handlers for " + h.type());
    var missing = EnumSet.complementOf(EnumSet.copyOf(byType.keySet()));
    if (!missing.isEmpty()) throw new IllegalStateException("no handler for " + missing);
}

Injecting by parent class BaseBookingService when the subclasses are beans too makes Spring guess by parameter name. Don't let wiring depend on variable names: use a registry or @Qualifier.

4. Working with AI

Hand to AI: generating an adapter from SDK docs, a table mapping error codes to an enum, conversion tests over many values.

Check yourself in AI-written code:

  • Money never goes through double or int; tests cover fractions, amounts below 1 and large amounts.
  • No SDK type, error code or exception leaks out of the adapter.
  • Timeouts and network errors yield "unknown" (Unknown, PAYMENT_PENDING), not "failed".
  • Every dependency in a @Service is private final.
  • A class named "Abstract Factory" really builds a family; if it only picks beans, rename it …Registry.

5. Exercises

Exercise 1: Review a wallet adapter

The wallet SDK has debit(account, amount, key), throws WalletDeclinedException on decline and IOException (including SocketTimeoutException) on network errors. The AI wrote an adapter and says "handles every error":

JAVA
try {
    return new Charged(sdk.debit(account, amountVnd, key));
} catch (WalletDeclinedException e) {
    return new Rejected(e.reason());
} catch (Exception e) {
    return new Rejected("NETWORK_ERROR");   // customer clicks "retry" with a new key
}
Solution 1

Two bugs:

  • On a read timeout the wallet may already have debited. Returning Rejected and retrying with a new key charges twice. Add Unknown(key, cause): the order sits in PAYMENT_PENDING, then query status with the same idempotency key or wait for the callback.
  • catch (Exception e) also swallows programming errors (IllegalArgumentException for a negative amount). Catch only IOException; bugs must surface.

Test: a fake SDK that records the debit and then throws SocketTimeoutException; assert the result is Unknown and there's no second debit.

Exercise 2: The "Abstract Factory" in the PR

The AI added the class below, described as "Abstract Factory picking a service by listing type". The first homestay booking throws an NPE. Name the bugs and the fix.

JAVA
@Service @RequiredArgsConstructor
public class BookingFactory {
    private final VillaBookingService villaBookingService;
    private HomestayService homestayService;
    private BaseBookingService baseBookingService;
}
Solution 2
  • Lombok only puts final fields in the constructor; homestayService and baseBookingService stay null. Add final.
  • With final added, several beans match BaseBookingService, so Spring relies on parameter names. Inject List<BookingHandler> into a registry instead.
  • Wrong name: it only picks existing beans, which is a simple factory. Rename it BookingHandlerRegistry.
  • Add a context-startup test that goes through every listing type.

Summary

  • An adapter translates types, units, error codes and exceptions; business code never sees the SDK.
  • Money is BigDecimal from a string or a long; round per Currency, convert once, store the rate.
  • A timeout is "unknown": reconcile with the same idempotency key.
  • Simple factory picks, Factory Method lets a subclass pick, Abstract Factory builds a family.
  • @RequiredArgsConstructor only injects final fields.

Further reading: IoC and Dependency Injection.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…
Next on the roadmapCode that humans and AI can read: naming, functions and control flow