Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Refactor this code so a new payment provider can be added without editing it:

Java
PaymentClient create(String type) {
switch (type) {
case "STRIPE": return new StripeClient(cfg);
case "ADYEN": return new AdyenClient(cfg);
default: throw new IllegalArgumentException(type);
}
}

Explain your choice in a Spring application.

I would replace the switch with a PaymentClientFactory interface that has a type() method and create(config), with one implementation per provider. In Spring, we inject List<PaymentClientFactory>, build a map from type to factory at startup, fail at startup if two factories claim the same type, and fail with a clear message for an unknown type at run time. A new provider is then a new class and the selection code never changes; for plugins delivered as separate jars, ServiceLoader gives the same structure without Spring. With only two stable providers, though, the switch may honestly be simpler.

Why this question is asked

Payment integrations change often: a new market needs a local provider, a contract ends, a provider is replaced for one region. If every change means editing a central switch, every change also risks breaking the providers that already work, and two teams adding providers at once collide in the same file. Interviewers ask this refactoring to see whether we can apply the open/closed principle with a real framework, and whether we know when not to. In this answer, we will see why the switch keeps changing, introduce a factory per provider, build the registry with Spring, look at what changed, do the same without Spring using ServiceLoader, and decide when the switch is still the right answer.

1Why the Switch Has to Change Every Time

The open/closed principle says a module should be open for extension but closed for modification: we should be able to add behaviour by adding code, not by editing code that already works. The switch breaks this, because it holds knowledge of every provider. Adding Mollie means opening the method, adding a case and a new import, and retesting the whole method.

The switch also mixes two responsibilities: knowing which providers exist, and knowing how to build each one. The refactoring separates them. Each provider knows how to build itself and what it is called; a small registry knows nothing about any provider in particular.

2A Factory per Provider

We define one small interface for creating clients, and one implementation per provider. Each factory declares the type it handles.

Java
public interface PaymentClientFactory {
String type(); // e.g. "STRIPE"
PaymentClient create(PaymentConfig config);
}
@Component
class StripeClientFactory implements PaymentClientFactory {
public String type() { return "STRIPE"; }
public PaymentClient create(PaymentConfig cfg) { return new StripeClient(cfg); }
}
@Component
class AdyenClientFactory implements PaymentClientFactory {
public String type() { return "ADYEN"; }
public PaymentClient create(PaymentConfig cfg) { return new AdyenClient(cfg); }
}

Notice that each factory is a Spring bean, so it can have its own dependencies injected, such as a provider-specific HTTP client or metrics, without the selection code knowing about them.

3Building the Registry at Startup

Spring can inject every bean of a type as a list. The registry turns that list into a map once, at startup, and uses it for every lookup.

Java
@Component
class PaymentClients {
private final Map<String, PaymentClientFactory> byType;
PaymentClients(List<PaymentClientFactory> factories) {
this.byType = factories.stream()
.collect(Collectors.toUnmodifiableMap(PaymentClientFactory::type, f -> f));
// two factories with type "STRIPE" -> IllegalStateException: Duplicate key STRIPE ...
// so the application fails to start
}
PaymentClient create(String type, PaymentConfig cfg) {
PaymentClientFactory f = byType.get(type);
if (f == null) {
throw new IllegalArgumentException(
"Unknown payment provider '" + type + "', known: " + byType.keySet());
}
return f.create(cfg);
}
}
clients.create("ADYEN", cfg); // AdyenClient
clients.create("PAYPAL", cfg); // IllegalArgumentException: Unknown payment provider 'PAYPAL', known: [STRIPE, ADYEN]
Step throughSelecting a client through the registry
SpringPaymentClientsAdyenClientFactoryCaller
inject List<PaymentClientFactory> at startup
build map: STRIPE, ADYEN; fail on duplicates
create("ADYEN", cfg)
create(cfg)
AdyenClient

5 messages in order. Play them, or step through them one at a time.

The registry never names a provider; it only looks them up.

Two failure modes are handled on purpose. A duplicate type is a programming error, so it should stop the application at startup, where a deployment pipeline will catch it, rather than silently letting one factory win. An unknown type comes from data, such as a merchant's configuration, so it fails at the call with a message that lists the known types, which saves a lot of time when someone mistypes a provider name.

4What Changed and Why It Matters

Adding Mollie is now one new class, MollieClientFactory, annotated as a component. The registry, the callers and the existing factories are untouched, so their tests do not need to change, and two teams adding two providers do not edit the same file. That is the open/closed principle in practice: the selection code is closed for modification, and the set of providers is open for extension.

There is a further benefit. Each provider's construction logic, such as reading its API keys or choosing its endpoints, lives next to its client, so the provider team owns it completely. And because the registry is a bean, tests can build it with a fake factory list to check the error handling without any real provider.

5The Same Structure Without Spring: ServiceLoader

If providers are delivered as separate jars, for example plugins that customers install, Spring may not be present, or the providers may not be known at build time. The JDK's ServiceLoader gives the same structure. Each provider jar declares its factory in a file named after the interface, or with a provides clause in module-info, and the application discovers all of them at run time.

Java
// In the Stripe jar: META-INF/services/com.shop.pay.PaymentClientFactory
com.shop.pay.stripe.StripeClientFactory
// Or in its module-info.java
provides com.shop.pay.PaymentClientFactory with com.shop.pay.stripe.StripeClientFactory;
// In the application
Map<String, PaymentClientFactory> byType = ServiceLoader.load(PaymentClientFactory.class)
.stream()
.map(ServiceLoader.Provider::get)
.collect(Collectors.toUnmodifiableMap(PaymentClientFactory::type, f -> f));

ServiceLoader requires each provider class to have a public no-argument constructor or a public static provider() method, so providers cannot receive injected dependencies the way Spring beans can. That is the trade: no container, but simpler providers.

6When the Switch Is Still the Right Answer

Refactoring has a cost: one interface, two extra classes and a registry, where there used to be a ten-line method. If the company has used Stripe and Adyen for five years and has no plans to add a third, the switch is easier to read, and the open/closed benefit is hypothetical. A modern switch expression with exhaustive cases over an enum would even make the compiler point out a missing provider.

So the honest answer is to refactor when change becomes frequent or when several teams need to add providers independently, typically when the third or fourth provider arrives. Until then, keep the switch small and well tested, and know which refactoring to apply when the time comes.

7Follow-up questions

Why inject a list rather than a map of bean names to factories?

Spring can inject a Map<String, PaymentClientFactory> keyed by bean name, but then the provider type becomes the bean name, which is fragile and easy to rename by accident. A type() method makes the key an explicit part of the contract, and building the map ourselves lets us check duplicates and normalise keys.

Should the factory create a new client on every call?

It depends on the client. Payment clients usually hold an HTTP connection pool and are safe to share, so the factory can cache one client per configuration, or the registry can create clients once at startup. Creating a new client per payment would waste connections.

How would you handle provider-specific configuration?

Give each provider its own typed configuration properties class bound from its own prefix, injected into its factory. The common PaymentConfig then carries only what every provider shares, such as merchant id and currency, and the registry stays free of provider details.

8Conclusion

In this answer, we replaced a switch over provider names with a PaymentClientFactory per provider, each declaring its type. Spring injects all factories as a list, and the registry builds a map at startup, failing fast on duplicate types and clearly on unknown ones. New providers are new classes, so the selection code stays closed for modification, ServiceLoader gives the same structure for separately delivered jars, and with only two stable providers the switch may still be the simpler choice.

What to say in the interviewAbout 80 seconds aloud

Open with

I would separate knowing which providers exist from knowing how to build each one. I define a PaymentClientFactory interface with a type method returning something like STRIPE, and a create method taking the config, and write one implementation per provider, each a Spring component so it can have its own dependencies.

Then, if they want more

Then a small PaymentClients registry takes a List of PaymentClientFactory in its constructor and builds an unmodifiable map from type to factory with toUnmodifiableMap. If two factories claim the same type, that throws a duplicate key exception and the application fails at startup, which is what I want for a programming error.

For an unknown type at run time I throw an IllegalArgumentException that lists the known types, because that usually comes from configuration. Adding a provider is now just a new class; the registry and the callers never change, which is the open/closed principle, and two teams can add providers without touching the same file.

If providers were plugins delivered as separate jars without Spring, ServiceLoader gives the same structure with a services file or a provides clause in module-info. But I would also say that with only two stable providers the switch is simpler, and I would refactor when changes become frequent.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Refactor this code so a new payment provider can be added without editing it:": https://scrivio-interview-library.netlify.app/java/creational-patterns/21a72dca63/