DEV Community

Vishwa
Vishwa

Posted on Originally published at Medium

UPI, Card or COD Without an if/else Chain: SOLID and the Strategy Pattern in Python

How one interface and a few small classes make adding a new payment method a one-class change

A shopping app's checkout supports UPI, card and cash on delivery. Before a big sale, the business asks for a fourth option, Pay Later, by Friday.

If the checkout code looks like the snippet below, Friday is going to be stressful.

The problem

def pay(kind, amount):
    if kind == "upi": ...
    elif kind == "card": ...
    elif kind == "cod": ...
    # adding Pay Later means editing this tested function
Enter fullscreen mode Exit fullscreen mode

Every new method means opening a function that already works and is already tested. The chain grows, each branch carries its own rules, and a change for one method can break another. The same chain usually gets copied into refunds and receipts too, so one new method becomes edits in several files.

This breaks the Open/Closed principle: code should be open for extension and closed for modification. Many if/elif branches on a "type" or "mode" are the usual smell.

The solution: one interface, one class per method

The Strategy pattern wraps each algorithm in its own class behind one interface, and the caller is handed the one it needs. Here, the algorithm is "how to take the money".

from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount): ...

class UPI(Payment):
    def pay(self, amount): return f"UPI: collect request for Rs {amount}"

class Card(Payment):
    def pay(self, amount): return f"Card: charging Rs {amount}"

class COD(Payment):
    def pay(self, amount): return f"COD: collect Rs {amount} at the door"

class Checkout:
    def __init__(self, payment: Payment):     # the strategy is passed in
        self.payment = payment

    def place_order(self, amount):
        return self.payment.pay(amount)       # no if/else on the type

for method in [UPI(), Card(), COD()]:
    print(Checkout(method).place_order(1499))
Enter fullscreen mode Exit fullscreen mode

Checkout no longer knows that UPI exists. It only knows the Payment contract. That is Dependency Inversion: depend on an abstraction and pass the concrete object in. It also makes testing easy, because a fake payment can be injected.

The user's choice still arrives as a string from the app, so something has to turn "cod" into a COD object. A small lookup table does that in one place, which is the Factory idea from the same set of patterns:

PAYMENTS = {"upi": UPI, "card": Card, "cod": COD}

def payment_for(choice):
    if choice not in PAYMENTS:
        raise ValueError(f"Unsupported payment method: {choice}")
    return PAYMENTS[choice]()

print(Checkout(payment_for("cod")).place_order(799))
Enter fullscreen mode Exit fullscreen mode

Now Friday's request is one new class and one line in the table. Checkout is not touched.

class PayLater(Payment):                      # new: nothing above changes
    def pay(self, amount): return f"PayLater: Rs {amount} due next month"

PAYMENTS["paylater"] = PayLater
print(Checkout(payment_for("paylater")).place_order(2999))
Enter fullscreen mode Exit fullscreen mode

Output of all three snippets run together:

UPI: collect request for Rs 1499
Card: charging Rs 1499
COD: collect Rs 1499 at the door
COD: collect Rs 799 at the door
PayLater: Rs 2999 due next month
Enter fullscreen mode Exit fullscreen mode

One more SOLID check: refunds. It is tempting to add refund() to Payment. But cash on delivery has nothing to refund through a gateway, so COD.refund() would raise an error, and a loop that refunds a batch of payments would crash halfway. That breaks Liskov Substitution: a child must work wherever the parent is used. The fix is a separate Refundable interface that only UPI and Card implement. This is also Interface Segregation: no class should be forced to carry methods it cannot honour.

Trade-offs and limits

  • Don't use it for two fixed options. If there will only ever be two branches, a plain if is clearer. I apply SOLID where change hurts, not everywhere.
  • Strategy is not Factory. The lookup table picks which class to build, once. The strategy is the behaviour that Checkout runs. Mixing up the two names is a common interview slip.
  • Python has no interface keyword. An abc class with only abstract methods plays that role.
  • Real payments need more than pay(). Idempotency keys, timeouts and webhooks still matter. The pattern organises that code; it does not replace it.

Takeaway

A long if/elif on a type is a design smell.

One interface, one class per method, and the caller gets the right one passed in.

New payment method = new class; old code stays closed.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The refunds section is the part that made this post worth reading twice, Vishwa — most Strategy write-ups stop at 'new class, no if/else', and yours goes one step further with the Liskov trap: a COD.refund() that raises halfway through a batch refund loop is exactly the kind of bug that passes every happy-path test. The piece I would add is the failure shape: a strategy that raises on a gateway timeout behaves very differently from one that returns a result object, and when you have three methods, the retry and idempotency logic ends up living in Checkout again unless each strategy returns the same result shape. One more small thing — the lookup table is where a typo becomes a runtime ValueError, so validating the choice once at the edge, where the string arrives, saves a confusing error deep in checkout. Which part was harder to get across when you wrote this — the Strategy itself, or the Refundable split?