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)
Fcqrs_550-modeling_002-change-nested-data.md_page.KindPersonalBusinessFcqrs_550-modeling_002-change-nested-data.md_page.PlainAccountKind: KindBalance: decimaldecimalAn abbreviation for the CLI type . Basic Types
checkBalance: PlainAccount -> Result<PlainAccount,string>account: PlainAccount(<): 'T -> 'T -> boolStructural less-than comparison The first parameter. The second parameter. The result of the comparison. 1 < 5 // Evaluates to true 5 < 5 // Evaluates to false (1, "a") < (1, "z") // Evaluates to true
ErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
OkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
withdrawPlain: decimal -> PlainAccount -> Result<PlainAccount,string>amount: decimalchangeKindPlain: Kind -> PlainAccount -> PlainAccountkind: Kindoverdrawn: Result<PlainAccount,string>(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Microsoft.FSharp.Core.ResultModuleContains operations for working with values of type . Choices and Results
map: ('T -> 'U) -> Result<'T,'TError> -> Result<'U,'TError>map f inp evaluates to match inp with Error e -> Error e | Ok x -> Ok (f x). A function to apply to the OK result value. The input result. A result of the input value after applying the mapping function, or Error if the input is Error. Ok 1 |> Result.map (fun x -> "perfect") // evaluates to Ok "perfect" Error "message" |> Result.map (fun x -> "perfect") // evaluates to Error "message"
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
FCQRSModelFCQRS.Model.DataConstrained value types and the `Value_` convention that makes them. A type has a private case and a static member `Value_`: a getter that reads the inner value and a setter that makes the type from it, returning `Result` when it can refuse. `ValueLens` creates and reads any such type, and `Value_` is also a lens that `FCQRS.Model.Aether` composes.
FCQRS.Model.ValidationRules for `Value_` setters and forms. `single` runs a chain of rules on one value, `all` and `fast` run them on several named fields, and `fieldValidation` joins values validated elsewhere and reports every field that failed.
FCQRS.Model.AetherOptics, after the Aether library: lenses and prisms read and set a part of a value. A validated lens has a setter that returns a Result, and every `Value_` member of a constrained type is one. `>->` from `Operators` joins optics, so a change deep inside a record runs the setter of each level, from the inside out.
FCQRS.Model.Aether.OperatorsOperators for optics: >-> and >?> compose, ^. reads.
Fcqrs_550-modeling_002-change-nested-data.md_page.DomainFcqrs_550-modeling_002-change-nested-data.md_page.Domain.AccountErrorBlankNotAnEmailOverdrawnOverLimitlimit: decimaldecimalAn abbreviation for the CLI type . Basic Types
Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.EmailEmailstringAn abbreviation for the CLI type . Basic Types
Value_: unit -> (Email -> string) * (string -> Email -> Result<Email,AccountError list>)_arg1: Emailaddress: stringsingle: (Validator<'E> -> 'T) -> Result<'T,'E list>Validates one value, as a `Value_` setter does, and returns its result or the errors as a list.
t: Validator<AccountError>TestOne: 'T -> FieldInfo<'T,'T,AccountError>(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Trim: FieldInfo<'T,string,AccountError> -> FieldInfo<'T,string,AccountError>Trims the value. It records no error, and leaves a null string for the next rule to refuse.
NotBlank: AccountError -> FieldInfo<'T,string,AccountError> -> FieldInfo<'T,string,AccountError>Validate with `String.IsNullOrWhiteSpace`
IsMail: AccountError -> FieldInfo<'T,string,AccountError> -> FieldInfo<'T,string,AccountError>Map: ('T0 -> 'T1) -> FieldInfo<'T,'T0,AccountError> -> FieldInfo<'T,'T1,AccountError>Map a function or constructor to the value, aka lift fn shouldn't throw error, if it would, please using `t.To fn error`
End: FieldInfo<'T,'T0,AccountError> -> 'T0Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.BalanceBalanceValue_: unit -> (Balance -> decimal) * (decimal -> Balance -> Result<Balance,AccountError list>)_arg3: Balanceamount: decimalOkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
Microsoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
listThe type of immutable singly-linked lists. See the module for further operations related to lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1; 2; 3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. See also F# Language Guide - Lists.
Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.AccountDataKind: KindFcqrs_550-modeling_002-change-nested-data.md_page.KindEmail: EmailBalance: BalanceFcqrs_550-modeling_002-change-nested-data.md_page.Domain.AccountAccountValue_: unit -> (Account -> AccountData) * (AccountData -> Account -> Result<Account,AccountError list>)_arg5: Accountdata: AccountDataResultValuebalance: decimalPersonal(<): 'T -> 'T -> boolStructural less-than comparison The first parameter. The second parameter. The result of the comparison. 1 < 5 // Evaluates to true 5 < 5 // Evaluates to false (1, "a") < (1, "z") // Evaluates to true
ErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
BusinessKind_: unit -> ValidatedLens<Account,Kind,AccountError list>ValidatedLensValidated Lens from 'a -> 'b with error type 'e.
_arg7: Accountkind: Kindaccount: Accountsnd: 'T1 * 'T2 -> 'T2Return the second element of a tuple, snd (a,b) = b. The input tuple. The second value. snd ("first", 2) // Evaluates to 2
Value_: (Account -> AccountData) * (AccountData -> Account -> Result<Account,AccountError list>)Email_: unit -> ValidatedLens<Account,Email,AccountError list>_arg8: Accountemail: EmailBalance_: unit -> ValidatedLens<Account,Balance,AccountError list>_arg9: Accountbalance: BalanceFCQRS.Model.Data.ValueLensCreates, reads, and rechecks any type that has a static member `Value_`, so a constrained type needs no `create` or `value` function of its own. type Email = private | Email of string static member Value_ = (fun (Email address) -> address), (fun (address: string) (_: Email) -> if address.Contains "@" then Ok(Email address) else Error [ "not an email" ]) let email: Result<Email, _> = ValueLens.TryCreate "alice@example.com" let text = email |> Result.map ValueLens.Value A setter that returns Result<'Wrapped, 'Error> is used with TryCreate; one that cannot refuse, such as a wrapper that reuses another type's rules, returns 'Wrapped and is used with Create or CreateAsResult. The setter's second argument is the current value, which TryCreate and Create pass as Unchecked.defaultof. A serializer builds the private case without the setter: check such data with IsValidValue.
TryCreate: 'Inner -> Result<^Wrapped,'Error>Creates a Result type depending the outcome of validation. The setter of Value_ receives Unchecked.defaultof<'Wrapped> as its second argument, so it must build the value from the inner value alone.
FCQRS.Model.Data.Resultvalue: Result<'a,'b> -> 'abalanceOf: decimal -> BalanceinDebt: Result<Account,AccountError list>alice: AccountinDebt 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_)
changeKind: Kind -> Account -> Result<Account,AccountError list>kind: KindFCQRS.Model.Aether.OpticReads, sets, and maps through any optic: Optic.get, Optic.set, Optic.map.
set: ^a -> 'b -> 'cSet a value using an optic.
Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.AccountKind_: ValidatedLens<Account,Kind,AccountError list>withdraw: decimal -> Account -> Result<Account,AccountError list>amount: decimalmap: ^a -> 'b -> 'cModify a value using an optic.
Balance_: ValidatedLens<Account,Balance,AccountError list>(>->): 'a -> ^b -> 'cCompose a lens with an optic or morphism.
Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.BalanceValue_: (Balance -> decimal) * (decimal -> Balance -> Result<Balance,AccountError list>)balance: decimal(-): ^T1 -> ^T2 -> ^T3Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8
changeEmail: string -> Account -> Result<Account,AccountError list>text: stringEmail_: ValidatedLens<Account,Email,AccountError list>Fcqrs_550-modeling_002-change-nested-data.md_page.Domain.EmailValue_: (Email -> string) * (string -> Email -> Result<Email,AccountError list>)refused: Result<Account,AccountError list>alice: Accountoverdraft: Result<Account,AccountError list>(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
BusinessMicrosoft.FSharp.Core.ResultModuleContains operations for working with values of type . Choices and Results
bind: ('T -> Result<'U,'TError>) -> Result<'T,'TError> -> Result<'U,'TError>bind f inp evaluates to match inp with Error e -> Error e | Ok x -> f x A function that takes the value of type T from a result and transforms it into a result containing a value of type U. The input result. A result of the output type of the binder. let tryParse (input: string) = match System.Int32.TryParse input with | true, v -> Ok v | false, _ -> Error "couldn't parse" Error "message" |> Result.bind tryParse // evaluates to Error "message" Ok "42" |> Result.bind tryParse // evaluates to Ok 42 Ok "Forty-two" |> Result.bind tryParse // evaluates to Error "couldn't parse"
backToPersonal: Result<Account,AccountError list>PersonalnotAnEmail: Result<Account,AccountError list>current: string(^.): 'a -> ^b -> 'cGet a value using an optic.
"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.IsValidValuereruns a type's own rule, not the rules of the values inside it. AccountDataalone carries no guarantee; takeAccountwhere 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.