Generics and templates
medium 45 minWrite a class or a function once, leave a blank for the type, and fill the blank at each use.
Video lesson · Chapter 1 of 5
Catch the error before the worker runs
See it run
Watch where a wrong type is noticed, what the compiler works out, and what is left when the program runs.
Operations
A box of Object
One file stores the wrong thing. Another file pays.
Step 1 of 4
Two files
Both use one box. The type of the content is Object.
Step 1: Two files
class Container: def store(self, item): self.item = item def retrieve(self): return self.itembox = Container()box.store(Phone())book = box.retrieve()book.read_page(1)- Noticed
- While running, in the reader
- Good to know
- A cast at each use
- Distance to the mistake
- another file
When a cast fails, ask who wrote the value, not who read it.
In the real world
The same generics and templates doing real jobs. Pick one and step through it.
One class in a storage hall. What goes in, what is refused?
Step 1 of 4
Books
| Made from one class | Accepted | Refused | |
|---|---|---|---|
| 1 | Container<Book> | a book | a phone |
| 2 | |||
| 3 |
T is Book. A phone is refused.
Step 1: Books
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Raw types
criticalOne raw variable switches the checks off for everything that goes through it.
WrongList names = new ArrayList(); // JavaRightList<String> names = new ArrayList<>();Silencing the warning
criticalUnchecked means that the compiler cannot keep its promise. The crash comes elsewhere.
Wrong@SuppressWarnings("unchecked")T get(String k) { return (T) map.get(k); }Right<T> T get(Key<T> key) { return key.kind.cast(map.get(key.name));}A letter that links nothing
minorT appears once. It is noise.
Wrong<T> void log(T x)Rightvoid log(Object x)Null for nothing
majorA list may contain null. The caller cannot tell the two apart.
Wrongreturn items[0] if items else None # T may be NoneRightif not items: raise LookupError('empty')return items[0]Trusting Python hints at run time
majorNothing is checked when it runs. Data from outside goes straight in.
Wrongids: list[int] = json.loads(text)Rightids = [int(x) for x in json.loads(text)]
Interview tips
Read a signature
- Find the letters
- Draw a line between equal ones
- Each line is a promise
Choose
- Called only: interface
- Comes back out: parameter
- Methods needed: bound
Traps
- Raw types
- Unchecked casts
- No new T() after erasure
Say
- Parameter and argument
- Erased, copied or kept
- Objects forget, headers remember