Smart constructor
Last updated
Was this helpful?
Last updated
Was this helpful?
π , 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
/ a Result
β Single-case (discriminated) union: Type X = private X of a: 'a...
π , Fβ― for fun and profit
β Record: Type X = private { a: 'a... }
π , 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
Smart constructor :
β tryCreate
function in companion module
β Returns an Option
Usages:
private
keyword has not exactly the same meaning in Fβ― as in Cβ―!
In Fβ―, private
indicates that the entity can be accessed only from the enclosing type or module.
In our example, private
is applied on the Latitude
definition that is on the Xxx.Types
module.
{ Latitude = ... }
and latitude.Latitude
are accessible in Xxx.Types
module as if there were no private
keyword.
In the 2nd code block, we are in another module. The Latitude
definition is not accessible.
We can use only Latitude.tryCreate
and latitude.Value
.
Smart constructor with:
Static method Of
Returns a Result
with a string
in the Error
track.