title: F# Record vs Class
body: <p>I used to think of a <code>Record</code> as a container for (immutable) data, until I came across some enlightening reading.</p>
  
  <p>Given that functions can be seen as values in F#, record fields can hold function values as well. This offers possibilities for state encapsulation.</p>
  
  <pre><code>module RecordFun =
  
      type CounterRecord = {GetState : unit -&gt; int ; Increment : unit -&gt; unit}
  
      // Constructor
      let makeRecord() =
          let count = ref 0
          {GetState = (fun () -&gt; !count) ; Increment = (fun () -&gt; incr count)}
  
  module ClassFun =
  
      // Equivalent
      type CounterClass() = 
          let count = ref 0
          member x.GetState() = !count
          member x.Increment() = incr count
  </code></pre>
  
  <p>usage</p>
  
  <pre><code>counter.GetState()
  counter.Increment()
  counter.GetState()
  </code></pre>
  
  <p>It seems that, apart from inheritance, there’s not much you can do with a <code>Class</code>, that you couldn’t do with a <code>Record</code> and a helper function. Which <a href="http://theburningmonk.com/2011/09/fsharp-record-types-vs-classes/" rel="noreferrer">plays better with functional concepts</a>, such as pattern matching, type inference, higher order functions, generic equality...</p>
  
  <p>Analyzing further, the <code>Record</code> could be seen as an <em>interface</em> implemented by the <code>makeRecord()</code> constructor. Applying (sort of) separation of concerns, where the logic in the <code>makeRecord</code> function can be changed without risk of breaking the <em>contract</em>, i.e. record fields.</p>
  
  <p>This separation becomes apparent when replacing the <code>makeRecord</code> function with a module that matches the type’s name (ref Christmas <a href="http://reedcopsey.com/2016/12/15/christmas-trees-in-wpf-2016-edition/#more-365" rel="noreferrer">Tree Record</a>).</p>
  
  <pre><code>module RecordFun =
  
      type CounterRecord = {GetState : unit -&gt; int ; Increment : unit -&gt; unit}
  
      // Module showing allowed operations 
      [&lt;CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)&gt;]
      module CounterRecord =
          let private count = ref 0
          let create () =
              {GetState = (fun () -&gt; !count) ; Increment = (fun () -&gt; incr count)}
  </code></pre>
  
  <p>Q’s: Should records be looked upon as simple containers for data or does state encapsulation make sense? Where should we draw the line, when should we use a <code>Class</code> instead of a <code>Record</code>?</p>
  
  <p><em>Note the model from the linked post is pure, whereas the code above is not.</em></p>