6 minute read

Don't model for the impossible

Encode invariants into your data types. Your domain model likes being richer than your database model.


insoftware design

When writing software we often end up with several views of the same business concept because across the data store, business logic, and published API contract the same domain type often looks different. This is often for a mix of reasons such as a partitioned or normalized data model (such as writing to more than one table in a DDD aggregate) or because we wish to conceal certain information from an API such as secrets or passwords.

Here's my thoughts on the most important things to encapsulate in a data model and when it's acceptable to simplify.

What makes a good domain model?

On an abstract level, a domain model encapsulates a domain resource for the domain use-cases that are applied to it. Sorry, that was a mouthful. In practice it means you're looking to model your data based on its "physical" attributes, and capabilities.

Additionally, we should also try to enforce invariants using our data model. If we can constrain the possible code paths to account for through clever modelling the code will be naturally easier to follow.

Our primary goal of domain modelling is to bake as much information about the problem into our data types.

In the very most primitive CRUD applications this often results in a model that enumerates a set of scalar attributes. A user resource might have givenName and familyName attributes, and more sensitive information such as passwordHash (I generally don't advise for handbaked auth, but this is merely an example). This is probably the simplest aggregate you can have, and I always strive for keeping things relatively simple, but the real world is often more complex.

Use algebraic data types (ADTs)

Quite often users are given a choice between one or more options to select from, such as whether to handle a payment using cash or a credit (or debit) card. When we model the corresponding PaymentMethod data type we should take this into account. Choices are represented by unions (either explicitly or implicitly) so we should model them as such. Each option often carries additional information, so the result is an algebraic data type (ADT)

enum PaymentMethod {
  Cash,
  CreditCard(CardInformation),
  DebitCard(CardInformation),
  // Here we've decided you can only use one method (or maybe each payment has
  // a set of PaymentMethod?) All depends on your business domain. In this
  // example we'll say there's only one method per purchase.
  LoyaltyProgram { points: u32 },
}

The underlying database model could look vastly different, but that's exactly the point. When we're modelling in business land we should not concern ourselves with how the underlying data store will look (although it can be useful to take into account). The better the data model encapsulates the real world, the simpler, organized, and readable the code becomes.

A weaker data model which more accurately reflects storage in a relational database can look like this:

struct NaivePaymentMethod {
  // Say we have single table inheritance (in DBMS speak)
  kind: &'static str, // or String, or an enum, if you want
  card_information: Option<CardInformation>,
  points_used: u32 // or even Option<u32>, what does Some(0) mean then?
}

Seeing as we have more clearly defined the business problem above (constraining ourselves to one payment method at a time), it is easy to argue this model sucks, but in reality the requirements are often dynamic and reveal themselves as time passes. It is unlikely you know what the domain model will look like in five years from today. It is fully believable that the naive model was a sensible model originally. Perhaps the business used to only accept cash.

ADTs reduce invariant checks

My biggest gripe with the weaker model presented above is that its design does not tell us anything about the legal combinations. Is it legal to use multiple payment methods? (Our other PaymentMethod design above says no). Should a procedure handling credit card information care about the points_used field?

The problem is that NaivePaymentMethod opens for many shapes, and does not communicate its capabilities. In the union, this is dead simple as each branch needs only concern itself with the variant given. For NaivePaymentMethod there are 16 possible shapes (two fields that are optional/zeroable, multiplied by the 4 known values of kind). However, our business use-case only considers four of them to be legal.

let by_credit_card = NaivePaymentMethod { kind: "cc", card_information: Some(...), points_used: 0, };
let by_debit_card = NaivePaymentMethod { kind: "debit", card_information: Some(...), points_used: 0, };
let by_loyalty = NaivePaymentMethod { kind: "loyalty", card_information: None, points_used: 2943, };
let by_cash = NaivePaymentMethod { kind: "cash", card_information: None, points_used: 0, };

// Not considered legal in our domain
let cannot_use_both = NaivePaymentMethod { kind: "cc", card_information: Some(...), points_used: 2943, };
// What?
let what = NaivePaymentMethod { kind: "points", card_information: None, points_used 0, };

Code processing the NaivePaymentMethod must add additional checks to enforce the invariants imposed by the business domain.

match payment_method.kind {
  "cc" => {
    // I don't advise for panicking in business code, but here for brevity.
    assert_eq!(payment_method.points_used, 0);
    let Some(c) = payment_method.card_information else {
      assert!(false);
    }
    ...,
  }
  _ => ...,
}

This code is not needed in the enum model, because the invariants are enforced at construction site, not usage site.

match payment_method {
  PaymentMethod::Card => ...,
  PaymentMethod::CreditCard(c) => ...,
  PaymentMethod::DebitCard(c) => ...,
  PaymentMethod::LoyaltyProgram { points } => ...,
}

A helpful programming language will also have an exhaustiveness check on this type of branch. That makes it impossible to forget when the underlying domain model changes as the code will fail type checking.

When should I break the rules?

Our task as software engineers is not necessarily to produce the most elegant or beautiful code. We're typically employed to fulfill some task that aligns with the goal of the business that's paying our paychecks. For that reason it can often be fair to make simplifications and break rules to accomplish and align with company goals (such as generic subdomains, tight deadlines, etc).

Summary

  • Unions map elegantly onto choices in a domain model.
  • Use algebraic data types to enforce your invariants, ensuring constructed data is legal. It's better to check once upon construction over checking every use.
  • You should optimize for the readability of the business code, not the database query code. Its preferred to write a mapping between database tables and domain model.
  • Break the rules whenever things are low-stake, relatively simple, or not worth investing time into, according to your company's current goals.

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