Java and Spring Level 2 This level · 64 of 84
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.

Could you say this in an interview?

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 (2)
  1. Spring — injecting collections of beans (@Autowired)docs.spring.io
  2. JEP 441 Pattern Matching for switchopenjdk.org
Previous
Next