Principle:ClickHouse ClickHouse Type Safe Wrappers
| Knowledge Sources | |
|---|---|
| Domains | Type_Safety, Patterns |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
A pattern that creates distinct types from base types to prevent implicit conversions and catch errors at compile time.
Description
Strong typedefs (also called opaque typedefs or newtype pattern) wrap an existing type in a distinct type that is not implicitly convertible. This prevents accidental misuse: you cannot pass a UserId where an OrderId is expected, even though both are integers internally. The pattern provides compile-time safety with zero runtime cost - the wrapper is optimized away completely.
Usage
Use when creating domain-specific types (IDs, handles, units of measurement), preventing type confusion, or improving API clarity.
Theoretical Basis
Type Safety: Distinct types prevent invalid operations at compile time rather than catching errors at runtime.
Zero-Cost Abstraction: Strong typedefs compile to the same machine code as raw types due to empty base optimization and inlining.
Compared to typedef/using: Regular aliases don't create new types, so they don't prevent conversions.
Newtype Pattern: Common in languages like Haskell and Rust; C++ achieves it with templates and tags.