Functional Patterns
Overview
Functional patterns leverage concepts from functional programming to write code that is more predictable, composable, and testable. These patterns emphasize immutability, pure functions, and declarative data transformations.
Patterns in This Category
| Pattern | Purpose | Key Mechanism |
|---|---|---|
| Higher-Order Functions | Pass and return functions as values | map, filter, reduce |
| Monad | Chain operations with context (errors, nulls) | Maybe, Result types |
| Immutability | Prevent state mutation after creation | Frozen / read-only objects |
| Currying | Transform multi-arg functions into chains | Partial application |
| Memoization | Cache function results by inputs | Lookup table / decorator |
| Pattern Matching | Destructure and branch on data shape | match/case, type switch |
| Lazy Evaluation | Defer computation until value is needed | Generators, thunks |
When to Use Functional Patterns
- Data pipelines: Higher-Order Functions, Lazy Evaluation
- Error handling without exceptions: Monad (Result/Maybe)
- Concurrent / parallel code: Immutability (no shared mutable state)
- Configuration and DSLs: Currying
- Performance optimization: Memoization, Lazy Evaluation
- Complex conditional logic: Pattern Matching
General Principles
- Prefer pure functions -- same input always produces same output, no side effects.
- Avoid mutation -- create new values instead of modifying existing ones.
- Compose small functions into larger transformations.
- Make illegal states unrepresentable using types (Monad pattern).
- Defer work until actually needed (Lazy Evaluation).