BBackend CourseLeroy Labs
0/0
Search the course

Ports & adapters, the Strategy pattern & pluggable providers

Hiding third parties behind interfaces, swapping implementations with config, stub adapters for dev and tests, and the Strategy pattern behind RM's report generators.

● intermediateSpring-Boot-StoreReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

Ports & adapters (hexagonal architecture)

Your domain defines what it needs as an interface (a port), in its own language. Adapters implement it for specific technologies.

// port: owned by the domain
public interface PaymentGateway {
    CheckoutSession createCheckoutSession(Order order);
    Optional<PaymentResult> parseWebhookRequest(WebhookRequest request);
}

// adapters: infrastructure
class StripePaymentGateway implements PaymentGateway { /* Stripe SDK */ }
class PaystackPaymentGateway implements PaymentGateway { /* Paystack REST */ }
class StubPaymentGateway implements PaymentGateway { /* always succeeds: dev/tests */ }

What you gain:

  • Testability. Services are tested with stubs, with no network.
  • Swappability. Changing provider touches one class.
  • Clean domain. No com.stripe.* imports in business code.
  • Local development without real credentials.

Strategy pattern

This is a family of interchangeable algorithms selected at runtime:

public interface ReportGenerationStrategy<Req, Res> {
    ReportType type();
    Res generate(Req request);
}

@Component class FinancialReportStrategy implements ReportGenerationStrategy<FinancialReportRequest, FinancialReportResult> { /* ... */ }
@Component class CashFlowReportStrategy  implements ReportGenerationStrategy<CashFlowRequest, CashFlowResult> { /* ... */ }

@Service
class ReportService {
    private final Map<ReportType, ReportGenerationStrategy<?, ?>> strategies;
    ReportService(List<ReportGenerationStrategy<?, ?>> all) {          // Spring injects every implementation
        strategies = all.stream().collect(toMap(ReportGenerationStrategy::type, s -> s));
    }
}

Adding a report type means adding a class, with no switch statements to edit. That’s the Open/Closed Principle.

In your projects

Spring-Boot-Storepayment/PaymentGateway · StripePaymentGateway

The first port/adapter you built: CheckoutService depends on PaymentGateway, not on Stripe.

IR3D (Kontentt)PaymentGateway · ContentMatchingService · ViewTrackingProvider · AdSenseProvider · SocialProfileVerifier · MediaStorageService

Six or more ports, each with a Stub and a Real adapter, chosen by properties (app.payments.provider, content-matching.provider, app.storage.provider). Developers run the whole platform locally without Paystack, TikTok or AWS keys. Content matching’s real adapter uses yt-dlp + ffmpeg frame sampling + perceptual hashing (PerceptualHasher, FrameSampler), which is expensive and external, so the stub is essential for tests.

Report-Manager-2module/report/application/*ReportStrategy.java

FinancialReportStrategy, CashFlowReportStrategy, IerReportStrategy, BankBalancesReportStrategy and FacultyIaeReportStrategy, each unit-tested separately (IerReportStrategyTest).

SperoTek (in dev)EmailTransport · BreachedPasswordChecker · OidcProvider · DnsTxtLookup

Ports for every external dependency: SMTP, Have I Been Pwned, OIDC providers and DNS. The tests replace HIBP and DNS with fakes, so they never call the internet.

Alternatives

  • Direct SDK calls. Fine for one-off scripts, but they couple you to a vendor.
  • Plain if/else or switch on type. Fine for 2–3 stable cases.
  • Spring @Profile-based beans instead of @ConditionalOnProperty. Profiles are coarser.
  • Plugin systems (ServiceLoader) for third-party extensions.
  • Anti-corruption layer (DDD). The adapter translates the vendor’s model into yours.
  • Contract tests for adapters. Run the same test suite against the stub and (occasionally) the real provider’s sandbox.
  • Fail-safe defaults. Make sure prod can’t start with StubPaymentGateway, using a startup check like SperoTek’s ProductionSecretsCheck.
  • Related GoF patterns: Adapter, Factory, Template Method, Decorator.

Check yourself

1. In hexagonal architecture, who owns the port interface?
2. Adding a new RM report type requires…