Generic programming

Also known as: generics

On this page 7

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.

ConceptMeaningExample
Type parameterA placeholder for a type supplied laterT in Box<T>
Generic typeA class, struct or interface with type parametersMap<K, V>
Generic functionA function with its own type parametersfn first<T>(items: &[T])
Constraint or boundA requirement a type argument must meetT: Display
InstantiationUse of a generic with concrete typesList<String>
VarianceHow subtyping of arguments affects the generic typeList<? extends Number>
Core concepts of generic programming

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.

LanguageStrategyMain consequence
C++Templates instantiated per typeFast code, larger binaries, long compile times
RustMonomorphization with trait boundsZero-cost abstraction, larger binaries
JavaType erasureNo primitive type arguments, types unavailable at run time
C#Reified generics with JIT specializationRun-time type information, value types without boxing
GoPartial monomorphization with dictionariesModerate binary size, some indirection
TypeScriptErased after type checkingNo run-time cost, no run-time type checks
How major languages implement generics

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.

TechniqueHow reuse is achievedType safetyTypical cost
Generic programmingType parameters with constraintsChecked at compile timeCode size or compile time
Subtype polymorphismShared base class or interfaceChecked, with possible downcastsVirtual dispatch at run time
Function overloadingSeparate function per typeChecked per overloadDuplicated code
Dynamic typingAny value accepted, checked when usedChecked at run timeErrors found later
Generic programming and related techniques

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.

SymptomTypical causeRemedy
Long, cryptic compiler errorsUnconstrained templates failing deep inside codeDeclare explicit constraints such as C++20 concepts
Binary size grows sharplyMonomorphization for many typesUse type-erased or dynamic dispatch for cold paths
Unchecked cast warnings in JavaType erasure combined with raw typesAvoid raw types and use bounded wildcards
Unreadable signaturesToo many type parametersIntroduce named type aliases or simplify the design
Frequent problems with generic code

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.