Generic programming is a style of programming in which algorithms and data structures are written in terms of types that are specified later, as type parameters, so that one implementation works correctly for many concrete data types. Among programming fundamentals it is the main technique for achieving reuse without giving up type safety.
Most mainstream languages support it under the name generics: Java, C#, Rust, Go, TypeScript and Swift all offer generic types and functions, while C++ provides the closely related mechanism of templates. A generic List<T> or max<T>(a, b) is written once and then instantiated for integers, strings or user-defined types.
How generic programming works
Generic programming works by abstracting over types in the same way that a function abstracts over values. A function such as swap(a, b) takes values as parameters; a generic function such as swap<T>(a: T, b: T) additionally takes a type parameter T, which the compiler fills in at each call site, usually through type inference.
Unrestricted type parameters allow only operations that every type supports. To do more, such as comparing or adding values, the programmer declares constraints, also called bounds: the type must implement an interface, trait or concept. A sorting function can therefore require T: Ord in Rust or T extends Comparable<T> in Java, and the compiler rejects calls with unsuitable types before the program runs.
The table below lists the core vocabulary of generic programming.
| Concept | Meaning | Example |
|---|---|---|
| Type parameter | A placeholder for a type supplied later | T in Box<T> |
| Generic type | A class, struct or interface with type parameters | Map<K, V> |
| Generic function | A function with its own type parameters | fn first<T>(items: &[T]) |
| Constraint or bound | A requirement a type argument must meet | T: Display |
| Instantiation | Use of a generic with concrete types | List<String> |
| Variance | How subtyping of arguments affects the generic type | List<? extends Number> |
Implementation strategies across languages
Languages implement generics with different strategies, and the choice shapes performance, binary size and run-time behavior. The two main approaches are monomorphization, in which the compiler generates a specialized copy of the code for each type, and type erasure, in which one shared implementation handles all types and the type arguments are checked only at compile time.
| Language | Strategy | Main consequence |
|---|---|---|
| C++ | Templates instantiated per type | Fast code, larger binaries, long compile times |
| Rust | Monomorphization with trait bounds | Zero-cost abstraction, larger binaries |
| Java | Type erasure | No primitive type arguments, types unavailable at run time |
| C# | Reified generics with JIT specialization | Run-time type information, value types without boxing |
| Go | Partial monomorphization with dictionaries | Moderate binary size, some indirection |
| TypeScript | Erased after type checking | No run-time cost, no run-time type checks |
The trade-off is classic: monomorphization favors speed, because each copy is optimized for its concrete type, while erasure favors compactness and simpler binary compatibility. Java’s erasure, for instance, explains why new T() is not allowed and why List<int> must be written as List<Integer>.
Generic programming compared with other forms of polymorphism
Generic programming is a form of parametric polymorphism: code behaves uniformly for all types that satisfy its constraints. It differs from subtype polymorphism, where code works through a common base class or interface, and from ad hoc polymorphism, where separate implementations are chosen per type, as with function overloading.
| Technique | How reuse is achieved | Type safety | Typical cost |
|---|---|---|---|
| Generic programming | Type parameters with constraints | Checked at compile time | Code size or compile time |
| Subtype polymorphism | Shared base class or interface | Checked, with possible downcasts | Virtual dispatch at run time |
| Function overloading | Separate function per type | Checked per overload | Duplicated code |
| Dynamic typing | Any value accepted, checked when used | Checked at run time | Errors found later |
In practice the techniques combine. A generic container may hold interface types, and dynamically typed languages such as Python add optional generic annotations so that static checkers can verify code that the interpreter itself never checks.
Where generics are used in practice
The most visible use is standard library collections: lists, maps, sets, queues and optional values are almost always generic. The C++ Standard Template Library, designed by Alexander Stepanov, demonstrated that algorithms can be separated from containers through iterators, so one sort works on any random-access sequence.
- Containers and wrappers:
Vec<T>,Optional<T>,Result<T, E>. - Algorithms: sorting, searching, mapping and filtering over any element type.
- Interfaces for services: repositories such as
Repository<Order>in business applications. - Asynchronous code: futures and promises such as
Promise<User>that carry the result type. - Callbacks and functions as values: typed signatures such as
Func<T, bool>.
In each case generics move errors from run time to compile time. A List<String> cannot accidentally receive an integer, which removes a whole category of casting errors common in older, non-generic code.
Limitations and common pitfalls of generics
Generic programming adds a layer of abstraction, and over-generalization is the most common mistake: code made generic for hypothetical future types becomes harder to read without delivering real reuse. A useful rule is to generalize only after the second or third concrete use.
| Symptom | Typical cause | Remedy |
|---|---|---|
| Long, cryptic compiler errors | Unconstrained templates failing deep inside code | Declare explicit constraints such as C++20 concepts |
| Binary size grows sharply | Monomorphization for many types | Use type-erased or dynamic dispatch for cold paths |
| Unchecked cast warnings in Java | Type erasure combined with raw types | Avoid raw types and use bounded wildcards |
| Unreadable signatures | Too many type parameters | Introduce named type aliases or simplify the design |
Variance rules are another frequent source of confusion. A list of cats is not automatically a list of animals, because allowing it would let code insert a dog. Languages resolve this with explicit annotations such as out T in Kotlin and C# or wildcards in Java.
In everyday language
Generic programming means writing a recipe once and letting it work with many ingredients. A recipe for “fruit jam” says what to do with the fruit without naming a specific fruit, so it works for strawberries, apricots or plums.
In the same way, a programmer writes one list or one sorting routine that works for numbers, names or customer records. The computer still checks that the ingredients fit, so nobody can put a stone into the jam by mistake.
Seen in the real world
A logistics company maintains a C# back-end service with separate data-access classes for shipments, drivers, depots and invoices. Each class repeats the same methods for loading, saving and paging records, about 300 lines per entity, and bugs fixed in one class are often missed in the others.
A senior developer replaces the four classes with one generic `Repository<TEntity>` constrained to types that implement an IEntity interface with an identifier. Entity-specific queries stay in small subclasses. The shared code shrinks to roughly 350 lines in total, a paging bug is now fixed in one place, and adding a new entity type for customs documents takes minutes instead of a day, with the compiler rejecting any attempt to save the wrong type.