A checkout that never changes
After this: Hand a payment method into Checkout, follow one order in a trace and a sequence diagram, and add a new kind without an edit.
On this page · 7 sections · 3 checks
Lesson 2 gave us three payment classes that keep one promise. Now we write the checkout that uses them. The goal from lesson 1 is that the checkout never asks "what are you?", so a new kind of payment never means editing it.
Hand the payment in
The checkout is a class with one field, method, and one method, place_orderplaceOrder. Its whole job is one line: pass the order to the payment method it holds, and return what that method says.
Part of Checkout | What it does |
|---|---|
the constructor, given method | keeps the payment method in a field |
| place_order(amount)placeOrder(amount) | returns self.method.pay(amount)method.pay(amount) |
This is delegation, as in "Composition over inheritance": the checkout holds a part and passes the work to it.
Where does the payment method come from? The checkout does not make it. The code outside makes a Card() or a Wallet(500) and hands it to the checkout when the checkout is made. The rule "hand the object in, do not create it inside" has a name: . Because of it, the checkout's code never names Card, Upi or Wallet.
Watch one loop
The program below is a short version for the trace: Card and Upi with only a pay each, and the checkout. The Python version leaves out the ABC; the Java version keeps a one-method interface, because Java needs a type for the list. The loop places an order of 1000 with each. The task asks you to watch the frame that opens for pay.
- Run the programRun it and step through. The loop makes a Checkout for each payment and calls its order method. Watch the frames: the order method opens a frame named pay. Read the first box of that pay frame (self in Python, this in Java) each time round the loop.
class Card: def pay(self, amount): fee = amount * 2 // 100 return "card charged " + str(amount + fee)
class Upi: def pay(self, amount): return "UPI paid " + str(amount)
class Checkout: def __init__(self, method): self.method = method
def place_order(self, amount): return self.method.pay(amount)
for m in [Card(), Upi()]: print(Checkout(m).place_order(1000))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The same line inside the checkout, self.method.pay(amount)method.pay(amount), ran twice. The first time the object in the field was a Card, so Card's pay ran and returned card charged 1020. The second time it was a Upi, and the line returned UPI paid 1000.
You met this idea in "Objects that share behaviour": one method name, and the object decides which version runs. It is called . In design, it is what lets the checkout stay the same while the kinds change.
Who talks to whom
A class diagram shows which classes exist. To show the order of calls in one run, designers draw a . Each object gets a box at the top and a dashed line going down, its . Time runs down the page.
Here is one order of 1250, paid by a wallet holding 500. Press Run it to send the messages one at a time.
Press Run it to send the messages one at a time.
- messages
- 0
- The customer calls place_order(1250)placeOrder(1250) on the checkout.
- The checkout calls
pay(1250)on the wallet. It does not know it is a wallet; it knows it is aPaymentMethod. - The wallet calls its own
fee(1250), which gives 12. The total is 1262. - 1262 is more than 500, so the wallet returns the refusal to the checkout, and the checkout returns it to the customer.
The whole program
Here is the checkout with the classes from lesson 2, and one more class, NetBanking, with a flat fee of 10. It was added at the bottom of the classes, and nothing else was changed for it.
from abc import ABC, abstractmethod
class PaymentMethod(ABC): @abstractmethod def fee(self, amount): ...
@abstractmethod def pay(self, amount): ...
class Card(PaymentMethod): def fee(self, amount): return amount * 2 // 100
def pay(self, amount): return f"card charged {amount + self.fee(amount)}"
class Upi(PaymentMethod): def fee(self, amount): return 0
def pay(self, amount): return f"UPI paid {amount}"
class Wallet(PaymentMethod): def __init__(self, balance): self.balance = balance
def fee(self, amount): return amount * 1 // 100
def pay(self, amount): total = amount + self.fee(amount) if total > self.balance: return f"wallet refused: needs {total}, has {self.balance}" self.balance -= total return f"wallet paid {total}, left {self.balance}"
# added later: no other class changesclass NetBanking(PaymentMethod): def fee(self, amount): return 10
def pay(self, amount): return f"netbanking paid {amount + self.fee(amount)}"
class Checkout: def __init__(self, method): self.method = method
def place_order(self, amount): return self.method.pay(amount)
for m in [Card(), Upi(), Wallet(500), Wallet(2000)]: print(Checkout(m).place_order(1250))
print(Checkout(NetBanking()).place_order(1250))card charged 1275 UPI paid 1250 wallet refused: needs 1262, has 500 wallet paid 1262, left 738 netbanking paid 1260
import java.util.List;
interface PaymentMethod { int fee(int amount); String pay(int amount);}
class Card implements PaymentMethod { public int fee(int amount) { return amount * 2 / 100; }
public String pay(int amount) { return "card charged " + (amount + fee(amount)); }}
class Upi implements PaymentMethod { public int fee(int amount) { return 0; }
public String pay(int amount) { return "UPI paid " + amount; }}
class Wallet implements PaymentMethod { private int balance;
Wallet(int balance) { this.balance = balance; }
public int fee(int amount) { return amount * 1 / 100; }
public String pay(int amount) { int total = amount + fee(amount); if (total > balance) { return "wallet refused: needs " + total + ", has " + balance; } balance -= total; return "wallet paid " + total + ", left " + balance; }}
// added later: no other class changesclass NetBanking implements PaymentMethod { public int fee(int amount) { return 10; }
public String pay(int amount) { return "netbanking paid " + (amount + fee(amount)); }}
class Checkout { private PaymentMethod method;
Checkout(PaymentMethod method) { this.method = method; }
String placeOrder(int amount) { return method.pay(amount); }}
public class Main { public static void main(String[] args) { for (PaymentMethod m : List.of(new Card(), new Upi(), new Wallet(500), new Wallet(2000))) { System.out.println(new Checkout(m).placeOrder(1250)); }
System.out.println(new Checkout(new NetBanking()).placeOrder(1250)); }}card charged 1275 UPI paid 1250 wallet refused: needs 1262, has 500 wallet paid 1262, left 738 netbanking paid 1260
The loop places an order of 1250 with each payment in the list:
- The card adds 25:
card charged 1275. - UPI has no fee:
UPI paid 1250. - The wallet with 500 needs 1262 and refuses.
- The wallet with 2000 pays 1262 and keeps 738.
The last line hands a NetBanking() to a new checkout: 1250 plus 10 is netbanking paid 1260.
The class diagram shows why that worked. Step through it, and look for the arrows that are not there.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
Checkout has one arrow, to PaymentMethod. Adding a kind adds a box and an arrow to the interface, and no arrow into Checkout. Designers call this programming to an interface: the code that uses an object depends on what it can do, not on its class.
Run it
Write a class Cash with no fee whose pay returns cash paid and the amount, put Cash() in the list, and run it. You did not touch Checkout.
Check yourself
The shop adds NetBanking, a new class that implements PaymentMethod. Which of the classes that already existed must be edited?
The loop now goes through four payments in this order: a Upi, a Wallet with 500, a Card and a Wallet with 2000. It places an order of 1250 through a Checkout for each. What are the four printed lines, in order?
Complete the one line inside place_orderplaceOrder, so that the checkout hands the work to the payment method it holds and returns what that method says. The program should print card charged 1275 and then UPI paid 1250.
from abc import ABC, abstractmethod
class PaymentMethod(ABC): @abstractmethod def fee(self, amount): ...
@abstractmethod def pay(self, amount): ...
class Card(PaymentMethod): def fee(self, amount): return amount * 2 // 100
def pay(self, amount): return f"card charged {amount + self.fee(amount)}"
class Upi(PaymentMethod): def fee(self, amount): return 0
def pay(self, amount): return f"UPI paid {amount}"
class Wallet(PaymentMethod): def __init__(self, balance): self.balance = balance
def fee(self, amount): return amount * 1 // 100
def pay(self, amount): total = amount + self.fee(amount) if total > self.balance: return f"wallet refused: needs {total}, has {self.balance}" self.balance -= total return f"wallet paid {total}, left {self.balance}"
class Checkout: def __init__(self, method): self.method = method
def place_order(self, amount): ____________________ # ← hand the work to the payment method
for m in [Card(), Upi()]: print(Checkout(m).place_order(1250))import java.util.List;
interface PaymentMethod { int fee(int amount); String pay(int amount);}
class Card implements PaymentMethod { public int fee(int amount) { return amount * 2 / 100; }
public String pay(int amount) { return "card charged " + (amount + fee(amount)); }}
class Upi implements PaymentMethod { public int fee(int amount) { return 0; }
public String pay(int amount) { return "UPI paid " + amount; }}
class Wallet implements PaymentMethod { private int balance;
Wallet(int balance) { this.balance = balance; }
public int fee(int amount) { return amount * 1 / 100; }
public String pay(int amount) { int total = amount + fee(amount); if (total > balance) { return "wallet refused: needs " + total + ", has " + balance; } balance -= total; return "wallet paid " + total + ", left " + balance; }}
class Checkout { private PaymentMethod method;
Checkout(PaymentMethod method) { this.method = method; }
String placeOrder(int amount) { ____________________ // ← hand the work to the payment method }}
public class Main { public static void main(String[] args) { for (PaymentMethod m : List.of(new Card(), new Upi())) { System.out.println(new Checkout(m).placeOrder(1250)); } }}Interview lens
- Write a Checkout that holds a payment method in a field and passes each order to it.
- Say what dependency injection means: the payment method is handed in from outside, not created inside.
- Follow one order in a sequence diagram: the calls go down the page, and the answers come back as dashed arrows.
- Add a new kind such as NetBanking as a new class, with no edit to Checkout or the other payments.
- Say why the missing arrow from Checkout to the concrete classes is the point of the design.