Video in progress

A new provider is added to the payment system every quarter. How do you build a design that follows the Open/Closed principle at the service and code level?

The domain only knows the PaymentProvider port; each provider is a separate adapter, registered automatically through Spring. The provider selection rule lives in configuration. Adding a provider means a new class and configuration, and the old code isn't touched.

📖 Answer

A bad start is a switch (provider) scattered everywhere: when creating a payment, checking status, refunding, in the webhook. A new provider means touching ten files and ten chances to make a mistake.

The port and the adapters:

public interface PaymentProvider {
    ProviderId id();
    Set<Capability> capabilities();          // REFUND, RECURRING, HOLD...
    ChargeResult charge(ChargeCommand cmd);
    RefundResult refund(RefundCommand cmd);
    WebhookEvent parseWebhook(HttpHeaders h, byte[] body); // also verifies the signature
}

@Component
class ProviderRegistry {
    private final Map<ProviderId, PaymentProvider> byId;
    ProviderRegistry(List<PaymentProvider> all) {
        byId = all.stream().collect(Collectors.toMap(PaymentProvider::id, p -> p));
    }
    PaymentProvider get(ProviderId id) { ... }
}

Where OCP breaks, and the fixes:

  • Differences in capabilities. Not every provider can refund. Instead of UnsupportedOperationException (an LSP violation), use capabilities() and have the domain check it up front.
  • Status mapping. Each provider has its own status codes: convert them to the domain status inside the adapter (a small ACL).
  • Webhook routing. /webhooks/{providerId}: one controller, and the right adapter comes from the registry.
  • The selection rule (by card type, amount, customer's country) isn't in code but in configuration or a separate routing strategy.

At the service level: if there are many providers and they belong to different teams, you can move each adapter into its own "connector" service, behind one contract. But that's not the starting point.

For every new adapter, write a shared set of contract tests (an abstract test class): idempotency, timeout, signature verification, refund limits. A new provider isn't enabled until it passes this suite. That way OCP works not only on the diagram but in quality too.