Lesson 1 · Unit 01
Depend on behaviour
Ask for what an object can do, not what it is
What you practise
- Duck typing, protocols and interfaces
- Callers that need only one method
- Composition over inheritance and the inheritance chain that breaks
Try a question from this lesson
Pick one
Robot shares no parent class with Dog. What does the last line do?
class Dog:
def speak(self):
return "woof"
class Robot:
def speak(self):
return "beep"
def announce(thing):
print(thing.speak())
announce(Robot())class Dog {
speak() { return "woof"; }
}
class Robot {
speak() { return "beep"; }
}
function announce(thing) {
console.log(thing.speak());
}
announce(new Robot());class Dog {
speak() { return "woof"; }
}
class Robot {
speak() { return "beep"; }
}
type Speaker = { speak(): string };
function announce(thing: Speaker) {
console.log(thing.speak());
}
announce(new Robot());Correct answer
Prints beep
Why
The function only calls speak(), so anything that can speak will do. Nobody asked what class the object is. Code that depends on behaviour accepts objects its author never heard of.
Python noteThis is duck typing: Python looks up speak on the object when the line runs and never checks the class.
TypeScript noteTypeScript checks shape, not ancestry. Robot matches Speaker because it has a speak(): string, with no implements anywhere.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Depend on behaviour
Write down the smallest thing a function needs from its argument. Here it is one method.
Any object with that method can be passed in: a real one, one from another library, a fake in a test. The function depends on a behaviour, and behaviours are easy to supply.
from typing import Protocol
class Speaker(Protocol):
def speak(self) -> str: ...
def announce(s: Speaker) -> str:
return s.speak() + "!"// anything with speak() will do
function announce(s) {
return s.speak() + "!";
}interface Speaker {
speak(): string;
}
function announce(s: Speaker): string {
return s.speak() + "!";
}Python noteA Protocol is duck typing written down. Classes never inherit from it; a type checker simply confirms that the argument has the method.
TypeScript noteAn interface lists what must exist. Any object with a matching speak satisfies it automatically.
Concept
Has-a beats is-a
Inheritance says "is a": the child gets everything the parent has, including how the parent's methods call each other.
Composition says "has a": your object holds another object and forwards the calls it wants. It depends only on what that object promises, so the insides can change without breaking you.
8 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.