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.
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
payment/PaymentGateway · StripePaymentGatewayThe first port/adapter you built: CheckoutService depends on PaymentGateway, not on Stripe.
PaymentGateway · ContentMatchingService · ViewTrackingProvider · AdSenseProvider · SocialProfileVerifier · MediaStorageServiceSix 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.
module/report/application/*ReportStrategy.javaFinancialReportStrategy, CashFlowReportStrategy, IerReportStrategy, BankBalancesReportStrategy and FacultyIaeReportStrategy, each unit-tested separately (IerReportStrategyTest).
EmailTransport · BreachedPasswordChecker · OidcProvider · DnsTxtLookupPorts 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/elseorswitchon type. Fine for 2–3 stable cases. - Spring
@Profile-based beans instead of@ConditionalOnProperty. Profiles are coarser. - Plugin systems (ServiceLoader) for third-party extensions.
Related concepts you must know
- 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’sProductionSecretsCheck. - Related GoF patterns: Adapter, Factory, Template Method, Decorator.