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 / a Result

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

Example #2

Smart constructor with:

  • Static method Of

  • Returns a Result with a string in the Error track.

Last updated

Was this helpful?