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

Generics and templates

1:02Reel

Theory

Read or listen first. About 2 min.

What it is

A generic class or function has a type parameter: a name such as T that stands for a type to be chosen later. Box<T> is written once. Box<String> and Box<Order> are uses of it. In C++ the same idea is called a template.

The parameter connects places. In T take() and put(T item) the same letter says: what comes out has the type of what went in. Object cannot say that. It says anything goes in, and something comes out.

A bound limits the choice: T extends Comparable<T> in Java, bound= in Python, a concept in C++20. The bound is also a permission. Inside the class you may use exactly what the bound promises.

This is static polymorphism, also called parametric. The compiler decides. Polymorphism under the hood shows the other kind, where the object decides while the program runs.

Why it exists

Without generics there are two bad choices. Write BookBox, PhoneBox and FoodBox with the same body, or write one box of Object and cast on the way out. The first repeats itself. The second moves mistakes from the compiler to the user.

With generics you get reuse and safety together. Wrong items are refused while you type. No casts are needed. And the type is documentation: Map<UserId, User> says more than Map.

It is also how libraries are built: lists, maps, futures, results, repositories, caches and event handlers are all generic. You read such signatures daily, so it pays to read them well.

A short history

  1. 1977

    The design of Ada begins. It has generics from the start and brings generic programming to the mainstream.

  2. 2004

    Java gets generics with J2SE 5.0. They are erased when compiled, so that old code keeps working.

  3. 2020

    C++20 adds concepts: templates can say what they need from a type.

  4. 2022

    Go 1.18 adds type parameters, in March. The Go team calls them the biggest change since the first open source release.

  5. 2023

    Python 3.12 adds short syntax from PEP 695: class Box[T] and def first[T](...).

Words to know

Type parameter
The blank in the definition, such as T, E, K, V.
Type argument
What you fill in: String in Box<String>.
Parameterised type
The generic with its blank filled: Box<String>.
Raw type
A Java generic used without its argument. It switches the checks off.
Bound
A condition on the argument, and the methods you may use.
Inference
The compiler finds the argument from the values you pass.
Type erasure
Arguments are checked and then removed from the running code.
Monomorphisation
The compiler makes one copy of the code for each argument. C++ and Rust do this.
Reified
Still known while the program runs, as in C#.
Bridge method
A hidden method that Java adds so that overriding still works after erasure.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Blank. Box<T>

Understand it

Start here

The bug jars

Some children collect small animals for a day. One sort of jar is enough for everything, if each jar has a tag and somebody checks it.

One plan, many tags
???

The smell

Object and casts

Java
class Container {    private Object item;    void store(Object item) { this.item = item; }    Object retrieve() { return item; }}Container box = new Container();box.store(new Phone());             // the mistake// ... 300 lines later, perhaps in another fileBook book = (Book) box.retrieve();  // ClassCastException here
It compiles. It fails far away from the mistake, when somebody else runs it.
Java
class Container<T> {    private T item;    void store(T item) { this.item = item; }    T retrieve() { return item; }}Container<Book> box = new Container<>();box.store(new Book("Java"));// box.store(new Phone());          does not compileBook book = box.retrieve();         // no castContainer<Food> lunch = new Container<>();   // same class, other type
With a type parameter the mistake is refused on its own line.

Three copies of one idea

BookBox- item: Book+ store(b: Book)+ retrieve(): Book

1/3A box for books

Safe and clear.

One box with a blank

Container<T>- item: T+ store(item: T)+ retrieve(): T

1/3The definition

Three places use T. They are tied together.

depends on

Whether Container<Dog> may stand in for Container<Animal> is a question of its own: covariance and contravariance.

What you gain

  • Type safety

    List<String> takes only strings. The error is on your screen, not in production.

  • No casts

    String s = list.get(0). The compiler knows.

  • Reuse

    One Box<T> for numbers, text and people.

  • Documentation

    Map<UserId, User> explains itself.

How it works

The life of a type argument

What the Java compiler does with your box

The cast did not disappear. The compiler writes it, and it can promise that it succeeds, as long as nobody used a raw type or an unchecked cast.

Four ways to implement generics

WayLanguagesAt run timePrice
ErasureJava, Kotlin on the JVM, TypeScriptOne copy of the code, no type argumentsNo new T(), no instanceof List<String>
One copy for each typeC++, RustSeparate code for each argumentLonger builds and larger programs
Kept typesC#Shared code for reference types, own code for value types, arguments knownA more complex runtime
HintsPythonNothing is checked. A checker reads the hints beforeA wrong value is noticed late if you skip the checker
Go leaves the choice to the compiler: the FAQ says that it may compile each instantiation separately or share similar ones.

Java: erasure

  • Types are checked when compiling
  • Old code from before 2004 still runs
  • One class file, however many uses
  • Declarations keep their signatures for reflection

C++: instantiation

  • New code for each type that you use
  • Full type information, when compiling
  • Can be specialised for one type
  • Can grow the program (code bloat)
Python
from typing import Generic, TypeVar, get_argsT = TypeVar("T")class Box(Generic[T]):    def put(self, item: T) -> None:        self.item = itembox = Box[int]()box.put("text")                        # a checker complains, Python does notprint(box.item, type(box) is Box)try:    isinstance(box, Box[int])          # cannot be askedexcept TypeError as error:    print("TypeError:", error)class IntBox(Box[int]):                # written in a class header: it is kept    passprint(get_args(IntBox.__orig_bases__[0]))
Python: the hint is for people and checkers. The program runs anyway.
Edit and run it in your browser
Python
class Box[T]:    def __init__(self) -> None:        self._items: list[T] = []def first[T](items: list[T]) -> T | None:    return items[0] if items else Nonedef biggest[C: Comparable](items: list[C]) -> C:   # C is bounded    ...
The short syntax of Python 3.12. The page uses the older one, so that it runs in more places.

Bounds

A limit that gives you methods

With a plain T you can store, pass and return a value. That is all, because T may be anything. To compare, add or save it, you need a promise. <T extends Number> refuses String and Boolean, accepts Integer, Long and Double, and lets you call doubleValue().

How to say it

NeedJavaTypeScriptPythonC++20
Any type<T><T>TypeVar("T")template <typename T>
Can be ordered<T extends Comparable<? super T>><T extends Comparable<T>>bound=Comparabletemplate <Comparable T>
Two promises<T extends A & B><T extends A & B>a Protocol with bothrequires A<T> && B<T>
One of a few typesnot possible<T extends number | string>TypeVar("T", int, str)std::same_as<T, int> || ...
Two parameters<E, ID><E, ID>Generic[E, ID]typename E, typename ID
TypeScript
interface Identifiable { id: string }interface Timestamped { createdAt: Date }function processEntity<T extends Identifiable & Timestamped>(entity: T): string {  return entity.id + " created " + entity.createdAt.toISOString();}function max<T extends number | string>(a: T, b: T): T {  return a > b ? a : b;}interface Repository<T, ID> {  findById(id: ID): T | null;  findAll(): T[];  save(entity: T): void;}
TypeScript: two promises at once, with an intersection.

Do I need a type parameter?

A type parameter that appears once in a signature links nothing. void print(T x) is the same as void print(Object x).

Java

Wildcards, in short

WildcardRead asExampleGood for
?some type, I do not careList<?>Size, printing, clearing. You can add nothing but null
? extends TT or a subtypeList<? extends Number>Reading: the list produces numbers
? super TT or a supertypeList<? super Integer>Writing: the list consumes integers
PECS: producer extends, consumer super. The reasons are in covariance and contravariance.
Java
double sum(List<? extends Number> numbers) {    double sum = 0;    for (Number n : numbers) sum += n.doubleValue();    return sum;}void addTwo(List<? super Integer> list) {    list.add(1);    list.add(2);}<T> void swap(List<T> list, int i, int j) {   // T is needed: out and in must agree    T old = list.get(i);    list.set(i, list.get(j));    list.set(j, old);}
<T> names the type so that you can use it twice. ? is for a type that you use once.

A method finds the first matching item of a list. Which signature?

BreaksObject find(List list, Predicate p)
How
Raw types.
Limit
The caller casts, and the checks for the whole call are off.
Choose when
Only to call code from before generics.
Works<T> T find(List<T> list, Predicate<T> p)
How
Linked, returns null when nothing matches.
Limit
A predicate for Object cannot be passed, and null is ambiguous.
Choose when
Private helpers.
Strong<T> Optional<T> find(Collection<? extends T> items, Predicate<? super T> p)
How
Accepts more callers and makes nothing visible.
Limit
Harder to read at first.
Choose when
A public method.

Neighbours

How it fits with other ideas

IdeaConnection
Covariance and contravarianceWhen one filled type may stand in for another
DRYGenerics remove the copies that differ only in a type
YAGNIA class with one use does not need a T yet
Interface segregationSmall interfaces make good bounds
StrategyComparator<T> is a generic strategy
LRU cacheCache<K, V> is the usual shape

Summary

The whole topic in one minute.

A type parameter is a blank that links places. Fill it, and the compiler checks what goes in and knows what comes out. A bound limits the types and gives you their methods. Use generics when the same code serves many types and the link between in and out matters.

Languages implement them differently. Java and TypeScript erase, C++ and Rust copy, C# keeps the types at run time. Python ignores the hints when running, and a checker reads them. Know which one you have, because it decides what you may ask at run time.

  • A type parameter links places: what goes in is what comes out
  • Errors move from run time to compile time, and casts disappear from your code
  • A bound limits the types and gives you their methods
  • Java erases, C++ copies, C# keeps, Python only hints
  • No new T(), no new T[n], no instanceof List<String> in Java: pass a Class<T> or a function
  • If T appears only once, use an interface instead

Sources