Back to Course

Practice · SOLID · OCP · Card 1

What goes wrong when you add a third payment type?

The code below works for two payment methods. Adding a third should be additive. The way this is structured, it isn't.

The code

A service that processes a payment. Two methods supported today.

class ProcessPayment
  def call(order, method)
    case method
    when :stripe
      Stripe::Charge.create(amount: order.total_cents, source: order.stripe_token)
      order.update!(paid_at: Time.current, payment_method: "stripe")
    when :paypal
      PayPal::Payment.create(amount: order.total_cents, payer: order.paypal_payer_id)
      order.update!(paid_at: Time.current, payment_method: "paypal")
    else
      raise "Unknown payment method: #{method}"
    end
  end
end

The question

You're asked to add Apple Pay. What's the OCP-flavored problem with how this code is shaped? And what's the shape of the fix?

Take a moment. Adding a new behavior should let you add code without changing existing code. What part of this design forces existing code to change every time the set of payment methods changes?