开发者

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 开发者_如何学Python_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


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 ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜