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.

1
2
3
4
5
6

  class Person {
    public Person(String name, String emailAddress, String phoneNumber) {
      /* .... */
    }
  }

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.

1
2
3
4
5
  class Person {
    public Person(Name name, EmailAddress emailAddress, PhoneNumber phoneNumber) {
      /* .... */
    }
  }

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.

1
2
3
4
5
6
7
  class Money {
      private BigDecimal value;

      String getFormatted() {
          value.format(...);
      }
  }

References

OO: Micro Types