AlgoViz

Generics and templates

medium 45 min

Write 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

0:00 / 4:52

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

writerfile Ahasa phoneboxContainertypeObjectitememptyreaderfile Bwantsa Book

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 classAcceptedRefused
1Container<Book>a booka 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

    critical

    One raw variable switches the checks off for everything that goes through it.

    Wrong
    List names = new ArrayList();   // Java
    Right
    List<String> names = new ArrayList<>();
  • Silencing the warning

    critical

    Unchecked 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

    minor

    T appears once. It is noise.

    Wrong
    <T> void log(T x)
    Right
    void log(Object x)
  • Null for nothing

    major

    A list may contain null. The caller cannot tell the two apart.

    Wrong
    return items[0] if items else None   # T may be None
    Right
    if not items:    raise LookupError('empty')return items[0]
  • Trusting Python hints at run time

    major

    Nothing is checked when it runs. Data from outside goes straight in.

    Wrong
    ids: list[int] = json.loads(text)
    Right
    ids = [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