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 }
SystemFcqrs_550-modeling_001-open-an-account.md_page.PlainAccountHolder: stringstringAn abbreviation for the CLI type . Basic Types
Email: stringBalance: decimaldecimalAn abbreviation for the CLI type . Basic Types
broken: PlainAccountNothing 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
Fcqrs_550-modeling_001-open-an-account.md_page.BookFcqrs_550-modeling_001-open-an-account.md_page.Book.HolderNameHolderNamestringAn abbreviation for the CLI type . Basic Types
Fcqrs_550-modeling_001-open-an-account.md_page.Book.HolderNameModulecreate: string -> Result<HolderName,string>text: stringname: stringTrim: unit -> stringstring: 'T -> stringConverts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattable, ToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10"
(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
ErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
Length: int(>): 'T -> 'T -> boolStructural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false
OkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
value: HolderName -> string_arg1: HolderNameEvery 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}"
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_550-modeling_001-open-an-account.md_page.DomainFcqrs_550-modeling_001-open-an-account.md_page.Domain.AccountErrorBlankTooLonglimit: intintAn abbreviation for the CLI type . Basic Types
NotAnEmailNotANumberNotPositiveEmailTakenFcqrs_550-modeling_001-open-an-account.md_page.Domain.HolderNameHolderNamestringAn abbreviation for the CLI type . Basic Types
Value_: unit -> (HolderName -> string) * (string -> HolderName -> Result<HolderName,AccountError list>)_arg1: HolderNamename: 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`
MaxLen: int -> AccountError -> FieldInfo<'T,'T0,AccountError> -> FieldInfo<'T,'T0,AccountError>Max length, if err is a string, it can contains `{len}` to reuse first param
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_001-open-an-account.md_page.Domain.EmailEmailValue_: unit -> (Email -> string) * (string -> Email -> Result<Email,AccountError list>)_arg3: Emailaddress: stringIsMail: AccountError -> FieldInfo<'T,string,AccountError> -> FieldInfo<'T,string,AccountError>Fcqrs_550-modeling_001-open-an-account.md_page.Domain.AmountAmountdecimalAn abbreviation for the CLI type . Basic Types
Value_: unit -> (Amount -> decimal) * (decimal -> Amount -> Result<Amount,AccountError list>)_arg5: Amountamount: decimalGt: 'a -> AccountError -> FieldInfo<'a0,'a,AccountError> -> FieldInfo<'a0,'a,AccountError>Greater then a value, if err is a string, it can contains `{min}` to reuse first param
holder: Result<HolderName,AccountError list>Microsoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
FCQRS.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.
nobody: Result<HolderName,AccountError list>notAnEmail: Result<Email,AccountError list>greet: HolderName -> stringholder 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 " "
Fcqrs_550-modeling_001-open-an-account.md_page.IdsFcqrs_550-modeling_001-open-an-account.md_page.Ids.AccountIdAccountIdFCQRS.Model.Data.ShortStringValidated non-blank string up to 255 chars inclusive.
Value_: unit -> (AccountId -> ShortString) * (ShortString -> AccountId -> AccountId)_arg1: AccountIdid: ShortStringaccountId: Result<AccountId,ModelError list>Microsoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
FCQRS.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.
CreateAsResult: 'a -> Result<^b,'d>Validates the inner value, returning its errors, then creates the parent with Create. A parent constructor that throws, such as CID's for '~', still throws.
blankId: Result<AccountId,ModelError list>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
Fcqrs_550-modeling_001-open-an-account.md_page.OpeningFormHolder: stringstringAn abbreviation for the CLI type . Basic Types
Email: stringDeposit: stringFcqrs_550-modeling_001-open-an-account.md_page.OpeningHolder: HolderNameFcqrs_550-modeling_001-open-an-account.md_page.Domain.HolderNameEmail: EmailFcqrs_550-modeling_001-open-an-account.md_page.Domain.EmailDeposit: AmountFcqrs_550-modeling_001-open-an-account.md_page.Domain.AmountparseDeposit: string -> Result<Amount,AccountError list>text: stringMicrosoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
System.DecimalRepresents a decimal floating-point number.
TryParse: string * IFormatProvider * byref<decimal> -> boolTries to parse a string into a value. The string to parse. An object that provides culture-specific formatting information about . When this method returns, contains the result of successfully parsing or an undefined value on failure. if was successfully parsed; otherwise, .
GlobalizationInvariantCulture: Globalization.CultureInfoGets the object that is culture-independent (invariant). The object that is culture-independent (invariant).
System.Globalization.CultureInfoProvides information about a specific culture (called a locale for unmanaged code development). The information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.
amount: decimalFCQRS.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.
ErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
NotANumbervalidate: OpeningForm -> Result<Opening,FieldErrors<AccountError>>form: OpeningFormfieldValidation: ValidationBuilderValidates several fields and reports every one that failed. Its name differs from FsToolkit.ErrorHandling's `validation`, whose errors are one list, so a file can open both: `fieldValidation { let! a = ... and! b = ... return f a b }`. Its result has the same type as `all`'s, so a field can also be a rule chain run with `all`.
holder: HolderName(|>): '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
field: string -> Result<'T,'E list> -> Result<'T,FieldErrors<'E>>Names the errors of a value validated elsewhere, such as by ValueLens.TryCreate, so that the `fieldValidation` builder can report them beside other fields': `let! email = input.Email |> ValueLens.TryCreate |> field "email"`. An `Error []` stays an Error, with the name and an empty list.
email: Emaildeposit: Amountwrong: OpeningFormeveryMistake: Result<Opening,FieldErrors<AccountError>>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" }
Fcqrs_550-modeling_001-open-an-account.md_page.AccountOpenedHolder: HolderNameFcqrs_550-modeling_001-open-an-account.md_page.Domain.HolderNameEmail: EmailFcqrs_550-modeling_001-open-an-account.md_page.Domain.EmailDeposit: AmountFcqrs_550-modeling_001-open-an-account.md_page.Domain.AmountBonus: decimaldecimalAn abbreviation for the CLI type . Basic Types
checkEmail: (Email -> bool) -> Opening -> Result<Opening,Map<string,AccountError list>>emailTaken: Email -> boolboolAn abbreviation for the CLI type . Basic Types
opening: OpeningFcqrs_550-modeling_001-open-an-account.md_page.OpeningErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
``.ctor``: (string * AccountError list) seq -> Map<string,AccountError list>Builds a map that contains the bindings of the given IEnumerable. The input sequence of key/value pairs. The resulting map. This is an O(n log n) operation, where n is the number of elements in the sequence. Map [ (1, "a"); (2, "b") ] // evaluates to map [(1, "a"); (2, "b")]
EmailTakenOkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
addBonus: Opening -> AccountOpenedResultValuedeposit: decimal(>=): 'T -> 'T -> boolStructural greater-than-or-equal The first parameter. The second parameter. The result of the comparison. 5 >= 1 // Evaluates to true 5 >= 5 // Evaluates to true [1; 5] >= [1; 6] // Evaluates to false
openAccount: (Email -> bool) -> OpeningForm -> Result<AccountOpened,FieldErrors<AccountError>>form: OpeningFormvalidate: OpeningForm -> Result<Opening,FieldErrors<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
Microsoft.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"
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"
_arg1: Emailaddress: string(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
opened: Result<AccountOpened,FieldErrors<AccountError>>Holder: stringEmail: stringDeposit: stringrefused: Result<AccountOpened,FieldErrors<AccountError>>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 withValueLens.IsValidValue. emailTakenanswers at the moment it is called; two requests can both see an address free. A unique index makes the rule hold.ValueLens.TryCreatepassesnullas 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.