Step 2: Keep a rule across fields

A personal account never goes below zero; a business account may overdraw down to -1000. Neither the kind nor the balance can check that alone.

A rule that every change must remember

type Kind =
    | Personal
    | Business

type PlainAccount = { Kind: Kind; Balance: decimal }

let checkBalance (account: PlainAccount) =
    match account.Kind with
    | Personal when account.Balance < 0m -> Error "overdrawn"
    | Business when account.Balance < -1000m -> Error "over the limit"
    | _ -> Ok account

let withdrawPlain amount (account: PlainAccount) =
    checkBalance { account with Balance = account.Balance - amount }

let changeKindPlain kind (account: PlainAccount) = { account with Kind = kind }

let overdrawn =
    { Kind = Business; Balance = 100m }
    |> withdrawPlain 150m
    |> Result.map (changeKindPlain Personal)

overdrawn is Ok with a personal account at -50: withdrawPlain called the rule and changeKindPlain forgot to.

The account checks itself

The account gets a Value_ like the values in step 1. Its fields are a public record, and its setter runs the rule on the whole record:

open FCQRS.Model.Data
open FCQRS.Model.Validation
open FCQRS.Model.Aether
open FCQRS.Model.Aether.Operators

module Domain =

    type AccountError =
        | Blank
        | NotAnEmail
        | Overdrawn
        | OverLimit of limit: decimal

    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))

    /// No rule of its own yet. Adding one later changes no field type and no caller.
    type Balance =
        private
        | Balance of decimal

        static member Value_ =
            (fun (Balance amount) -> amount),
            (fun (amount: decimal) (_: Balance) -> (Ok(Balance amount): Result<_, AccountError list>))

    type AccountData = { Kind: Kind; Email: Email; Balance: Balance }

    type Account =
        private
        | Account of AccountData

        static member Value_ =
            (fun (Account data) -> data),
            (fun (data: AccountData) (_: Account) ->
                let (ResultValue balance) = data.Balance

                match data.Kind with
                | Personal when balance < 0m -> Error [ Overdrawn ]
                | Business when balance < -1000m -> Error [ OverLimit 1000m ]
                | _ -> Ok(Account data))

        static member Kind_: ValidatedLens<Account, Kind, AccountError list> =
            (fun (Account data) -> data.Kind),
            (fun kind (Account data as account) -> snd Account.Value_ { data with Kind = kind } account)

        static member Email_: ValidatedLens<Account, Email, AccountError list> =
            (fun (Account data) -> data.Email),
            (fun email (Account data as account) -> snd Account.Value_ { data with Email = email } account)

        static member Balance_: ValidatedLens<Account, Balance, AccountError list> =
            (fun (Account data) -> data.Balance),
            (fun balance (Account data as account) ->
                snd Account.Value_ { data with Balance = balance } account)

open Domain

let email: Email = ValueLens.TryCreate "alice@example.com" |> Result.value
let balanceOf amount : Balance = ValueLens.TryCreate amount |> Result.value

let inDebt: Result<Account, _> =
    ValueLens.TryCreate { Kind = Personal; Email = email; Balance = balanceOf -50m }

let alice: Account =
    ValueLens.TryCreate { Kind = Personal; Email = email; Balance = balanceOf 100m }
    |> Result.value

inDebt is Error [Overdrawn]. Result.value unwraps a value known to be valid.

Each field lens on Account copies the record and passes it to Account.Value_'s setter, so a change to any field runs the account's rule. The lenses belong to Account, not AccountData: a lens on the record could change a field without the rule.

Balance has no rule today, and its setter always returns Ok. It is wrapped anyway: a rule added later, such as a maximum, goes into its Value_, and AccountData, its stored shape, and every caller stay as they are.

Change fields through the lenses

>-> from FCQRS.Model.Aether.Operators joins an account lens with a value's Value_. The result reads and changes the field's inner value, and runs the value's rules and then the account's:

let changeKind kind = Optic.set Account.Kind_ kind
let withdraw amount = Optic.map (Account.Balance_ >-> Balance.Value_) (fun balance -> balance - amount)
let changeEmail text = Optic.set (Account.Email_ >-> Email.Value_) text

let refused = withdraw 150m alice
let overdraft = alice |> changeKind Business |> Result.bind (withdraw 150m)
let backToPersonal = overdraft |> Result.bind (changeKind Personal)
let notAnEmail = changeEmail "alice" alice
let current = alice ^. (Account.Email_ >-> Email.Value_)
"alice" -> Email's rules -> data with the new email -> Account's rule -> account

refused is Error [Overdrawn]. overdraft is Ok at -50, because a business account may overdraw, and backToPersonal is Error [Overdrawn]: the change changeKindPlain let through. No function can skip the rule, because the only way to get an Account is its setter. notAnEmail is Error [NotAnEmail], and the account rule did not run. current is "alice@example.com". No type has a create or value function.

A one-off change with no lens is ValueLens.Map or ValueLens.Bind on the account, which run its setter on the changed record: alice |> ValueLens.Map(fun data -> { data with Kind = Business }).

Where the guarantee ends

  • A serializer skips Value_. ValueLens.IsValidValue reruns a type's own rule, not the rules of the values inside it.
  • AccountData alone carries no guarantee; take Account where the rule matters.

An FCQRS aggregate stores events and rebuilds an account from them: the CQRS tutorial. A process that calls other services and must continue after a crash is a workflow.