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
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
1977
The design of Ada begins. It has generics from the start and brings generic programming to the mainstream.
2004
Java gets generics with J2SE 5.0. They are erased when compiled, so that old code keeps working.
2020
C++20 adds concepts: templates can say what they need from a type.
2022
Go 1.18 adds type parameters, in March. The Go team calls them the biggest change since the first open source release.
2023
Python 3.12 adds short syntax from PEP 695:
class Box[T]anddef first[T](...).
Words to know
- Type parameter
- The blank in the definition, such as
T,E,K,V. - Type argument
- What you fill in:
StringinBox<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.
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.
The smell
Object and casts
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 hereclass 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 typeThree copies of one idea
1/3A box for books
Safe and clear.
One box with a blank
1/3The definition
Three places use T. They are tied together.
depends on
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
Four ways to implement generics
| Way | Languages | At run time | Price |
|---|---|---|---|
| Erasure | Java, Kotlin on the JVM, TypeScript | One copy of the code, no type arguments | No new T(), no instanceof List<String> |
| One copy for each type | C++, Rust | Separate code for each argument | Longer builds and larger programs |
| Kept types | C# | Shared code for reference types, own code for value types, arguments known | A more complex runtime |
| Hints | Python | Nothing is checked. A checker reads the hints before | A wrong value is noticed late if you skip the checker |
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)
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]))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 ...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
| Need | Java | TypeScript | Python | C++20 |
|---|---|---|---|---|
| Any type | <T> | <T> | TypeVar("T") | template <typename T> |
| Can be ordered | <T extends Comparable<? super T>> | <T extends Comparable<T>> | bound=Comparable | template <Comparable T> |
| Two promises | <T extends A & B> | <T extends A & B> | a Protocol with both | requires A<T> && B<T> |
| One of a few types | not 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 |
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;}Do I need a type parameter?
void print(T x) is the same as void print(Object x).Java
Wildcards, in short
| Wildcard | Read as | Example | Good for |
|---|---|---|---|
? | some type, I do not care | List<?> | Size, printing, clearing. You can add nothing but null |
? extends T | T or a subtype | List<? extends Number> | Reading: the list produces numbers |
? super T | T or a supertype | List<? super Integer> | Writing: the list consumes integers |
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
nothingvisible. - Limit
- Harder to read at first.
- Choose when
- A public method.
Neighbours
How it fits with other ideas
| Idea | Connection |
|---|---|
| Covariance and contravariance | When one filled type may stand in for another |
| DRY | Generics remove the copies that differ only in a type |
| YAGNI | A class with one use does not need a T yet |
| Interface segregation | Small interfaces make good bounds |
| Strategy | Comparator<T> is a generic strategy |
| LRU cache | Cache<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(), nonew T[n], noinstanceof List<String>in Java: pass aClass<T>or a function - If T appears only once, use an interface instead
Sources
- Oracle tutorial: Type erasure
- Oracle tutorial: Bridge methods
- Oracle tutorial: Restrictions on generics
- Java API: Collections
- Guice: TypeLiteral
- Jackson: TypeReference
- Spring Data: CrudRepository
- The Rust book: generic data types
- .NET: Generics in the runtime
- Go blog: An introduction to generics
- cppreference: Constraints and concepts
- PEP 695: Type parameter syntax
- TypeScript handbook: Generics