ก่อนที่เราจะเริ่ม implement ขั้นตอนต่างๆ ของ workflow เอง เราต้อง implement “simple type” ก่อน เช่น OrderId และ ProductCode .
เนื่องจาก type ส่วนใหญ่ถูกจำกัดด้วยเงื่อนไขบางอย่าง เราจะทำตามแนวทางการ implement constrained type ที่เรา คุยกันไปก่อนหน้านี้ .
ดังนั้น สำหรับ simple type แต่ละตัว เราจะต้องมี function อย่างน้อยสองตัว:
-
function create ที่สร้าง type จากค่า primitive เช่น string หรือ int —ตัวอย่างเช่น OrderId.create จะสร้าง OrderId จาก string หรือคืน error ถ้า string มีรูปแบบที่ไม่ถูกต้อง
-
function value ที่ดึงค่า primitive ด้านในออกมา
โดยทั่วไปเราจะใส่ helper function เหล่านี้ไว้ในไฟล์เดียวกับ simple type นั้น โดยใช้ module ที่มีชื่อเดียวกับ type ที่มันเกี่ยวข้อง ตัวอย่างเช่น นี่คือนิยามของ OrderId ใน module Domain พร้อมกับ helper function ของมัน:
| | module Domain = |
| | type OrderId = private OrderId of string |
| | |
| | module OrderId = |
| | /// Define a "Smart constructor" for OrderId |
| | /// string -> OrderId |
| | let create str = |
| | if String.IsNullOrEmpty(str) then |
| | // use exceptions rather than Result for now |
| | failwith "OrderId must not be null or empty" |
| | elif str.Length > 50 then |
| | failwith "OrderId must not be more than 50 chars" |
| | else |
| | OrderId str |
| | |
| | /// Extract the inner value from an OrderId |
| | /// OrderId -> string |
| | let value (OrderId str) = // unwrap in the parameter! |
| | str // return the inner value |
-
function create คล้ายกับเวอร์ชันในแนวทางที่เราคุยกันไว้ ต่างกันตรงที่เนื่องจากตอนนี้เรายังหลีกเลี่ยง effect อยู่ เราจะใช้ exception ( failwith ) สำหรับ error แทนที่จะคืนค่าเป็น Result .
-
function value แสดงให้เห็นว่าคุณสามารถ pattern-match และดึงค่าด้านในออกมาได้ในขั้นตอนเดียว โดยทำโดยตรงใน parameter.