Boss lesson · Unit 01
Pass it in
Hand a class its collaborators instead of letting it build them
What you practise
- Dependency inversion and injection: a checkout that builds its own payment client against one that is handed it
- Fakes in tests
- Where the wiring goes
Try a question from this lesson
Pick one
You want to test pay without charging a real card. What is in the way?
class Bank:
def charge(self, cents):
print("REAL CHARGE", cents)
class Checkout:
def __init__(self):
self.bank = Bank()
def pay(self, cents):
self.bank.charge(cents)
return "paid"class Bank {
charge(cents) {
console.log("REAL CHARGE", cents);
}
}
class Checkout {
bank = new Bank();
pay(cents) {
this.bank.charge(cents);
return "paid";
}
}class Bank {
charge(cents: number): void {
console.log("REAL CHARGE", cents);
}
}
class Checkout {
bank = new Bank();
pay(cents: number): string {
this.bank.charge(cents);
return "paid";
}
}Correct answer
Checkout builds its own Bank, so a test cannot swap it
Why
The class reaches out and constructs the real bank itself. Every Checkout, in every test, talks to the real thing. The collaborator is welded in.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Dependency injection
Hand the collaborator in instead of building it inside. The class says what it needs in its constructor, and whoever creates it decides what it gets.
Production passes the real bank. A test passes a fake. The class cannot tell the difference, and does not need to.
class Checkout:
def __init__(self, bank):
self.bank = bank
def pay(self, cents):
self.bank.charge(cents)
return "paid"
shop = Checkout(Bank())class Checkout {
constructor(bank) {
this.bank = bank;
}
pay(cents) {
this.bank.charge(cents);
return "paid";
}
}
const shop = new Checkout(new Bank());class Checkout {
constructor(private bank: Bank) {}
pay(cents: number): string {
this.bank.charge(cents);
return "paid";
}
}
const shop = new Checkout(new Bank());TypeScript notebank: Bank uses the class as a type, and TypeScript compares shapes: any object with a charge(cents: number): void is accepted, subclass or not.
Concept
Where the wiring goes
Someone still has to create the real objects. Do it once, at the top: in main, or wherever the program starts.
That one place knows every concrete class. Everything below it only receives what it needs. To see how the app is assembled, you read one function.
def main():
bank = Bank()
shop = Checkout(bank)
shop.pay(500)
main()function main() {
const bank = new Bank();
const shop = new Checkout(bank);
shop.pay(500);
}
main();function main(): void {
const bank = new Bank();
const shop = new Checkout(bank);
shop.pay(500);
}
main();9 more exercises in the app
- 1× fill the blanks
- 2× type the answer
- 1× true or false
- 4× multiple choice
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.