Smart constructor
Purpose
π Making illegal states unrepresentable, Fβ― for fun and profit
Design to prevent invalid states
Encapsulate state (all primitives) in an object
Smart constructor guarantees a valid initial state
Validates input data
If Ko, returns "nothing" (
Option) or an error (Result)If Ok, returns the created object wrapped in an
Option/ aResult
Encapsulate the state in a type
β Single-case (discriminated) union: Type X = private X of a: 'a...
π Designing with types: Single case union types, Fβ― for fun and profit
β Record: Type X = private { a: 'a... }
π You Really Wanna Put a Union There? You Sure?, by Paul Blasucci
β private keyword:
Hide object content
Fields and constructor no longer visible from outside
Smart constructor defined in companion module or static method
Example #1
Smart constructor :
β tryCreate function in companion module
β Returns an Option
Usages:
Access control
private keyword has not exactly the same meaning in Fβ― as in Cβ―!
In Fβ―,
privateindicates that the entity can be accessed only from the enclosing type or module.In our example,
privateis applied on theLatitudedefinition that is on theXxx.Typesmodule.{ Latitude = ... }andlatitude.Latitudeare accessible inXxx.Typesmodule as if there were noprivatekeyword.In the 2nd code block, we are in another module. The
Latitudedefinition is not accessible.We can use only
Latitude.tryCreateandlatitude.Value.
Example #2
Smart constructor with:
Static method
OfReturns a
Resultwith astringin theErrortrack.
Last updated
Was this helpful?