When to Use Generic Classes vs Functions
You'll learn how to decide between stateful generic classes and stateless generic functions based on your use case needs.
The Core Decision
The choice between generic classes and generic functions comes down to state:
- Generic functions are best for stateless, single operations that transform or process data
- Generic classes are best when you need to store and manage state across multiple operations
Think of it like cooking: a generic function is like a recipe that takes ingredients and returns a dish. A generic class is like a kitchen appliance that you configure once, then use repeatedly while maintaining settings.
When to Choose Generic Functions
Use generic functions when:
- You're performing a one-time transformation
- No state needs to persist between calls
- The operation is a pure input-to-output mapping
// Good: Stateless filtering operation
function filter<T>(array: T[], predicate: (item: T) => boolean): T[] {
return array.filter(predicate);
}
const numbers = filter([1, 2, 3, 4], n => n > 2); // [3, 4]
const words = filter(['hi', 'hello'], w => w.length > 2); // ['hello']
When to Choose Generic Classes
Use generic classes when:
- State must be stored and reused
- Multiple related operations share the same type context
- Configuration happens once, usage happens many times
// Good: Stateful collection management
class Container<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getAll(): T[] {
return this.items;
}
}
const numbers = new Container<number>();
numbers.add(1);
numbers.add(2);
Key Takeaway: Choose generic functions for stateless transformations and generic classes when you need to encapsulate state with type-specific behavior across multiple operations.