7 minute read

Branded types are really awesome

Branded types are typically advocated as type-safe identifiers. I use them to communicate intent.


insoftware design

Branded types are scalar data types with a unique name attached to them. They are most often used to distinguish different identifier types, but I think they are a core domain modelling utility. In this post I discuss how you can use branded types to supplement your domain modelling process, places I like to use them, and what I believe they should look like to minimize developer friction.

Branded types primer

If you're new to branded types I will present a quick introduction to them. If you already know what they are you can feel free to skip this section.

Branded types are wrapper types (newtypes) around another data type such as String. What makes branded types are unique, meaning two branded types wrapping the same inner type may not be assigned to eachother. This is useful because it lets your type checker ensure you do not assign a UserId to a StoreId.

The implementation of a branded type depends on the programming language you use, and its way of representing unique types. In languages that use nominal typing such as Rust and Java they essentially wrap another type, while structural languages like TypeScript require extra workarounds.

#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct UserId(pub uuid::Uuid);
public value record UserId(UUID id) {}
declare const __brand: unique symbol;
type UserId = string & { [__brand]: 'user' };
function makeUserId(value: string): UserId {
  return value as UserId;
}

Branded types are particularly useful in large business domains where a single function may track many different resource types. Branded types make it impossible to accidentally pass the wrong type.

// No longer possible to mix the two arguments because identifiers are branded
// and typescript will not allow passing a PostId to arguments asking for
// UserId.
async function deleteBlogCommentsByUser(user: UserId, post: PostId) { ... }

Branded types convey semantic context

Domain modelling is one of the first problems we tackle when building new features (at least in typical web services). The real world is complex and often unnecessarily detailed for many business use cases, so we spend a great amount of effort settling for a domain model that can fulfill our business use case.

When modelling the real world, we want to capture as much context about the problem in our model. If there are business constraints we should try to encode those using invariants and ensure our software reflects the business process. That is the general premise about domain driven design. We want to put the business use-case first.

Concepts often have a semantic meaning attached to them. A 64-bit integer representing a monetary sum as i64 conveys less information than the branded type struct Money(i64); does. The Money type makes it obvious to any reader what the number's intended use is. If relevant, we could also attach additional constraints to the construction of this type, such as requiring a non-zero amount.

In anti-corruption layers against third parties

Web services often communicate with other web services. We consume APIs, write to databases, and submit telemetry. Identifiers and values from external system often have additional constraints. It is for example known that an AWS Cognito user subject is a UUID string, and an AWS S3 bucket URL starts with s3://.

pub struct AWSCognitoUserSubject(uuid::Uuid);

In system architecture an anti-corruption layers is an interface between us and another system. By adding a thin layer over the external service we can shield ourselves from extensive changes when the external system undergoes backwards incompatible changes. By using branded types for identifiers and other key types from the third-party system it is easier to track (using your editor) how far the third-party service reaches into your system, and how dependent you truly are on it.

It also doubles as additional documentation on where the value came from.

As application configuration

Configuration parameters often have set formats or guidelines. We can remove a host of problems by ensuring the individual parameter values are valid when the application starts.

If our service uses AWS SQS as a Pub/Sub queue and the SQS queue is configurable I will create a branded type for the parameter. It should be named according to the context it is intended to be used in. In this example we are sending outbound SMS messages, and queue these using SQS.

// Also validate the SQS URL too here to ensure it's in the format of
// https://sqs.<region>.amazonaws.com/<accountid>/<queue>
public value record SMSMessageQueue(String sqsUrl) { ... }

It is now impossible to mess up and cross-contaminate/use the wrong queue for the wrong purpose. Since we validate the SQS queue upon application launch it is also impossible to have delayed faults due to invalid queue URLs.

How to succeed with branded types?

The largest tax of branded types is additional indirection and verbosity. In TypeScript we can assign the branded type to its inner type so no extra code is required. In Rust, however, we need to access the inner struct value with id.0 (although it can be partially avoided by abusing the Deref/DerefMut traits). This adds additional code and does impact readability. An ideal implementation of branded types should strive to reduce the amount of extra code.

At runtime we may also pay an additional cost to access the inner value. Luckily the Rust compiler and JVM don't incur this extra charge, but if your programming language is unable to remove the additional cost of indirection (i.e, pointer dereference) then you want to be aware of the extra performance tax1.

Additional code from using branded types should be viewed as a trade-off between terseness and expressiveness + correctness of code. I prefer choosing correctness and communication of intent.

Appendix: Rust user? Use macros!

If you use Rust you probably scoffed over my Rust example earlier. The newtype loses all trait capabilities of the inner type, and we would have to re-derive/re-implement any interesting trait for the newtype. This is a tedious process because if you wrap the String type you are probably interested in implementing Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd2, and a number of other traits. It is luckily quite easy to implement a macro for automatically deriving these traits if the inner type dervies them by abusing Higher-Rank Trait Bounds (HRTBs).

pub trait Branded {
    type Inner;
}

// Then given some struct pub struct UserId(Inner), make the macro produce this
// code:
impl Hash for UserId
where
    for<'__brand> <Self as Branded>::Inner: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        (&self.0).hash(state);
    }
}

// For example, using the syn and quote crates.
fn expand_hash_impl(brand_struct_name: &syn::Ident) -> proc_macro2::TokenStream {
    let hash_trait: syn::Path = syn::parse_quote!(::std::hash::Hash);
    quote! {
        impl #hash_trait for #brand_struct_name
        where
            for<'__branded> <Self as Branded>::Inner: #hash_trait,
        {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                (&self.0).hash(state);
            }
        }
    }
}

Once upon a time I also made a small crate for doing this.

Footnotes

  1. If you are writing traditional web services, the dereference of this pointer will be practically free compared to your I/O costs, but it is nice to remember that not all abstractions (most in fact) are not free. ↩

  2. Implementing PartialOrd and Ord traits are very useful if your service performs cursor pagination on k-sortable identifiers. ↩


Blog content licensed under CC BY-NC-SA 4.0 DEED. No language models were used in the creation of the content.