Step 1: Open an account

This section models a bank account in the style of Scott Wlaschin's Domain Modeling Made Functional, with the package FCQRS.Model and nothing else from FCQRS. The package depends only on FSharp.Core and compiles under Fable. Every line of code is on the page, and the page runs as an F# script.

dotnet add package FCQRS.Model

Plain types accept anything

open System

type PlainAccount = { Holder: string; Email: string; Balance: decimal }

let broken = { Holder = "   "; Email = "not an email"; Balance = -50m }

Nothing refused broken: string accepts every string and decimal every number.

A type per rule, with two functions each

The book gives each constrained value its own type with a private case, so the only way to make one is a create function that checks it, and a value function reads it back:

module Book =

    type HolderName = private HolderName of string

    module HolderName =
        let create (text: string) =
            let name = (string text).Trim()

            if name = "" then Error "blank"
            elif name.Length > 100 then Error "too long"
            else Ok(HolderName name)

        let value (HolderName name) = name

Every type repeats create and value, and code that changes a field inside a record calls both by hand at each level.

One member instead: Value_

FCQRS.Model replaces the pair with one static member, Value_: a getter and a setter that checks. ValueLens.TryCreate and ValueLens.Value work for every type that has one, and the rules are written with the validator from FCQRS.Model.Validation:

open FCQRS.Model.Data
open FCQRS.Model.Validation

module Domain =

    type AccountError =
        | Blank
        | TooLong of limit: int
        | NotAnEmail
        | NotANumber
        | NotPositive
        | EmailTaken

    type HolderName =
        private
        | HolderName of string

        static member Value_ =
            (fun (HolderName name) -> name),
            (fun (name: string) (_: HolderName) ->
                single (fun t ->
                    t.TestOne name
                    |> t.Trim
                    |> t.NotBlank Blank
                    |> t.MaxLen 100 (TooLong 100)
                    |> t.Map HolderName
                    |> t.End))

    type Email =
        private
        | Email of string

        static member Value_ =
            (fun (Email address) -> address),
            (fun (address: string) (_: Email) ->
                single (fun t ->
                    t.TestOne address
                    |> t.Trim
                    |> t.NotBlank Blank
                    |> t.IsMail NotAnEmail
                    |> t.Map Email
                    |> t.End))

    type Amount =
        private
        | Amount of decimal

        static member Value_ =
            (fun (Amount amount) -> amount),
            (fun (amount: decimal) (_: Amount) ->
                single (fun t ->
                    t.TestOne amount
                    |> t.Gt 0m NotPositive
                    |> t.Map Amount
                    |> t.End))

open Domain

let holder: Result<HolderName, _> = ValueLens.TryCreate " Alice "
let nobody: Result<HolderName, _> = ValueLens.TryCreate "   "
let notAnEmail: Result<Email, _> = ValueLens.TryCreate "alice"

let greet (ResultValue name: HolderName) = $"Welcome, {name}"

holder is Ok with "Alice", nobody is Error [Blank], and notAnEmail is Error [NotAnEmail]. The pattern ResultValue reads the inner value, as greet does. Outside Domain, HolderName " " does not compile. Because Value_ is a getter and a setter, it is also a lens, which step 2 uses to change fields deep inside a record.

A type that only reuses another type's rules has a setter that cannot fail. ValueLens.CreateAsResult runs the inner type's rules and wraps the result:

module Ids =

    type AccountId =
        private
        | AccountId of ShortString

        static member Value_ = (fun (AccountId id) -> id), (fun id (_: AccountId) -> AccountId id)

open Ids

let accountId: Result<AccountId, _> = ValueLens.CreateAsResult "ACC-1"
let blankId: Result<AccountId, _> = ValueLens.CreateAsResult "   "

blankId is Error [EmptyString], from ShortString. FCQRS's own CID and AggregateId are built this way.

Report every mistake in a form

Result.bind stops at the first error. The fieldValidation builder checks every field joined with and!, and field names each field's errors:

type OpeningForm = { Holder: string; Email: string; Deposit: string }

type Opening = { Holder: HolderName; Email: Email; Deposit: Amount }

let parseDeposit (text: string) : Result<Amount, _> =
    match Decimal.TryParse(text, Globalization.CultureInfo.InvariantCulture) with
    | true, amount -> ValueLens.TryCreate amount
    | false, _ -> Error [ NotANumber ]

let validate (form: OpeningForm) =
    fieldValidation {
        let! holder = form.Holder |> ValueLens.TryCreate |> field "holder"
        and! email = form.Email |> ValueLens.TryCreate |> field "email"
        and! deposit = form.Deposit |> parseDeposit |> field "deposit"
        return ({ Holder = holder; Email = email; Deposit = deposit }: Opening)
    }

let wrong: OpeningForm = { Holder = ""; Email = "alice"; Deposit = "-5" }
let everyMistake = validate wrong
Error (map [("deposit", [NotPositive]); ("email", [NotAnEmail]); ("holder", [Blank])])

The whole process as one function

Opening an account refuses an email another account uses and grants a bonus of 10 for a deposit of 1000 or more. The lookup is a function parameter, so a test passes a set and the program a query:

type AccountOpened = { Holder: HolderName; Email: Email; Deposit: Amount; Bonus: decimal }

let checkEmail (emailTaken: Email -> bool) (opening: Opening) =
    if emailTaken opening.Email then Error(Map [ ("email", [ EmailTaken ]) ]) else Ok opening

let addBonus (opening: Opening) : AccountOpened =
    let (ResultValue deposit) = opening.Deposit

    { Holder = opening.Holder
      Email = opening.Email
      Deposit = opening.Deposit
      Bonus = if deposit >= 1000m then 10m else 0m }

let openAccount emailTaken form =
    validate form |> Result.bind (checkEmail emailTaken) |> Result.map addBonus

let emailTaken (ResultValue address: Email) = address = "bob@example.com"

let opened = openAccount emailTaken { Holder = " Alice "; Email = "alice@example.com"; Deposit = "1200" }
let refused = openAccount emailTaken { Holder = "Bob"; Email = "bob@example.com"; Deposit = "50" }

opened is Ok with a bonus of 10, and refused is Error (map [("email", [EmailTaken])]). addBonus takes an Opening, so it never sees a negative deposit, and its result is not a Result: it cannot fail.

Where the guarantee ends

  • A serializer builds the private case without calling Value_. Check data read from JSON or a database with ValueLens.IsValidValue.
  • emailTaken answers at the moment it is called; two requests can both see an address free. A unique index makes the rule hold.
  • ValueLens.TryCreate passes null as the setter's second argument, so a setter must not read it.

A rule about several fields together, such as a personal account that never goes below zero, is step 2.