MiloDC
MiloDC

Reputation: 2415

F#: Closures vs. private values

Assuming no further modifications or additions will be made to the following type, is there any advantage to doing this one way vs. the other (apart from the less typing and better readability and efficiency of the second example)?

    type MyType<'T> (_initVal : 'T) =
        let getSetFns () =
            let value = ref _initVal
            (fun () -> value.Value), (fun _value -> value := _value)
        let getVal, setVal = getSetFns ()
        member this.Value with get () = getVal () and set _value = setVal _value

... or...

    type MyType<'T> (_initVal : 'T) =
        let value = ref _initVal
        member this.Value with get () = value.Value and set _value = value := _value

Upvotes: 1

Views: 177

Answers (1)

Robert
Robert

Reputation: 6437

The second one is shorter, so I'd go for that. You may want to consider using let mutable rather than a reference cell, it will be slightly more performant (though it's unlikely you'll notice much difference).

To give a little more context, using closures to hide values, as you do in the first case, is a good technique, but here the value is already hidden, so why bother hiding it again ?

Upvotes: 5

Related Questions