Tiny Types
Tiny or Micro types wrap primitive types in a class to provide stronger typing and cohesive functionality.
Rationale
When using Tiny Types the compiler helps prevent errors with mismatching types, e.g. passing a name into an email address that may need to be constructed with a valid email format. Tiny types also makes interfaces clearer, e.g. a method accepts a valid email address instead of a string.
Implications
- Consider immmutability when creating tiny types.
- Tiny types may need methods to enable their content to be easily visible when debugging.
Stronger typing example
In this example we are passed a primitive to the constructor of a person.
|
|
In this example primitives have been wrapped in their own class. This avoids errors where any of the parameters can mixed, e.g. passing the email address as the name.
|
|
Cohesive functionality example
Here, rather than representing money as a bare BigDecimal we have wrapped it in a class, allowing us to keep the formatting of monetary value close to the definition.
|
|