Medium java spring

New payment method added; PaymentService is a giant if-else on type?

The 30 second answer

You have to edit and retest the central class every time, which violates Open/Closed, grows fragile branches, and fails at runtime when a case is forgotten. I refactor to Strategy: one processor interface, one Spring bean per payment method, and a map from type to processor. A new method is a new class. With a sealed interface and pattern-matching switch, the compiler can flag missing cases instead.

You must edit and re-test the central class each time (violates Open/Closed), branches grow, and a forgotten branch fails at runtime. Refactor to Strategy: interface PaymentProcessor { PaymentType type(); Result pay(Request r); }, one Spring bean per method, and inject List<PaymentProcessor> into a Map<PaymentType, PaymentProcessor>. New method = new class. With a sealed interface + pattern-matching switch, the compiler flags missing cases instead.

interface PaymentProcessor {
    PaymentType type();
    Result pay(Request r);
}

Inject List<PaymentProcessor> and build a Map<PaymentType, PaymentProcessor> so a new method is a new class.

Sources:

Sources (0)
See inline citations in the answer above.